I've got this code so far, which isn't working:
$('.passName').click(function(){
var schoolName = "18734";
var link = $(this).attr('href');
var newLink = link + schoolName;
$(this).attr('href') = newLink;
});
I've got this code so far, which isn't working:
$('.passName').click(function(){
var schoolName = "18734";
var link = $(this).attr('href');
var newLink = link + schoolName;
$(this).attr('href') = newLink;
});
Share
Improve this question
edited Feb 5, 2013 at 16:14
dfsq
193k26 gold badges242 silver badges259 bronze badges
asked Feb 5, 2013 at 16:08
dezmandezman
19.4k13 gold badges57 silver badges92 bronze badges
5
-
$(this).attr('href') = newLink;
gets an error – dezman Commented Feb 5, 2013 at 16:09 - Some context into how this is being used and what isn't working would be helpful. – simnom Commented Feb 5, 2013 at 16:09
- The problem with changing a link onclick is that your link will grow if you open targeting another tab... – Denys Séguret Commented Feb 5, 2013 at 16:10
-
Try this shorthand:
$(this).attr('href', $(this).attr('href') + '18734')
– Khez Commented Feb 5, 2013 at 16:11 - 1 @watson: That's not how you use .attr. – Matt Burland Commented Feb 5, 2013 at 16:11
4 Answers
Reset to default 11Do the following:
$(this).attr('href', newLink);
There is a problem with your approach : you're appending the schoolName to the URL each time you click, even if the user targets another tab.
So I'd suggest to not mess with the href
attribute but do the action on click :
$('.passName').click(function(){
location.href = this.href + "18734";
});
or at least check you didn't add it before :
$('.passName').click(function(){
var schoolName = "18734";
var link = this.href;
if (link.indexOf(schoolName, link.length - schoolName.length)!==-1) {
this.href = link+schoolName
}
});
or, as suggested by Felix Kling, simply ensure the function is called only once :
$('.passName').one('click', function(){
this.href += "18734"
});
In Simple, do this way:-
$('.passName').click(function() {
$(this).attr('href', this.href+'18734');
});
You actually don't need to create a new jQuery object, you can simply have:
$('.passName').click(function() {
var schoolName = "18734";
this.href += schoolName;
});
Library as jQuery as useful but we shouldn't forgot the plain JavaScript and DOM.
Plus, in JS you can't really "assign" something to a function call as you made; in jQuery the way to set an attribute's value is $(this).attr('attr', newLink)