What's a cleaner way to add something to the link url?

I have this code so far that doesn't work:

$('.passName').click(function(){
    var schoolName = "18734";
    var link = $(this).attr('href');
    var newLink = link + schoolName;
    $(this).attr('href') = newLink;
});

      

+3


source to share


4 answers


Follow these steps:



$(this).attr('href', newLink);

      

+11


source


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


At its simplest, do this: -

$('.passName').click(function() {
    $(this).attr('href', this.href+'18734');
});

      

+1


source


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







All Articles