سؤال

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;
});
هل كانت مفيدة؟

المحلول

Do 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)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top