最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Whats a cleaner way to append something to a link URL? - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 11

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)

发布评论

评论列表(0)

  1. 暂无评论