Reputation: 1411
I'm changing my link urls to add www.site.com/index.html?s=234&dc=65828
what I'm getting with this code is: site.com/&dc=65828
var target="&dc=65828";
$("a").attr({
href: "" + target
});
Can someone show me where I'm going wrong.
Upvotes: 1
Views: 8912
Reputation: 76
Don't you guys believe in error-checking?
$('a').attr('href', function(i, currentAttribute){
// don't clutter up the global namespace
var target="dc=65828";
// if it's already there, don't double-do it
if (currentAttribute.indexOf(target) >= 0){
return currentAttribute;
}
// if we've got a query string already
if (currentAttribute.indexOf('?') >= 0){
return currentAttribute + '&' + target;
}
// if we've not got a query string yet
return currentAttribute + '?' + target;
});
Upvotes: 1
Reputation: 78681
This would be the elegant way to solve this:
var target="&dc=65828";
$('a').attr('href', function(i, currentAttribute){
return currentAttribute + target;
});
The function you pass as the second parameter will receive the current href
attribute in its second parameter (I named it currentAttribute
for better readability). Whatever you return from this function will be set as the new href
attribute.
This approach works fine on more than one links and does not use an unnecessary .each()
.
Upvotes: 3
Reputation: 1770
Check this out this is will give the exact match result
$('a').append(function(){
$(this).attr('href', $(this).attr('href')+target);
});
$('a').html(function(){
$(this).attr('href', $(this).attr('href')+target);
});
Upvotes: -1
Reputation: 22728
There's a couple of things.
First:
href: ""+target
Will set your link to be only:
&dc=65828
You'll need to something like:
$('a').attr('href', $(this).attr('href')+target);
But that's assuming that ?s=234
is already on the end of the link. If not you'll need to add that too.
Upvotes: -1
Reputation: 20191
I would do it like this:
var target="&dc=65828";
$(function(){
$('a').each(function(){
$(this).attr('href', $(this).attr('href')+target);
});
});
Upvotes: 3
Reputation: 5231
Try this:
var target="&dc=65828",
$link = $("a");
$link.attr('href', $link.attr('href') + target);
Upvotes: -2