What's a cleaner way to add something to the link url?
4 answers
The problem with your approach: you add the school name to the url every time you click, even if the user clicks on another tab.
So my suggestion is not to bind to the attribute href
, but to perform an action on click:
$('.passName').click(function(){
location.href = this.href + "18734";
});
or at least check that you haven't added 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 Felix Kling suggested, just make sure the function is called only once:
$('.passName').one('click', function(){
this.href += "18734"
});
+8
source to share
You don't need to create a new jQuery object, you can simply:
$('.passName').click(function() {
var schoolName = "18734";
this.href += schoolName;
});
A library like jQuery as useful, but we mustn't forget plain JavaScript and DOM.
Also, in JS, you cannot "assign" anything to a function call like you did; in jQuery way to set attribute value$(this).attr('attr', newLink)
0
source to share