Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

attributes - Changing a links href after click with jQuery

I am trying to create a link that when clicked on, switches its href attribute, and then goes to that location.

My html is:

<a href="http://google.com" rel="group" data-wpurl="http://yahoo.com"></a>

When clicked, I would like the browser to go to the data-wpurl location, not href location. The reason I am using a data attribute is because of the application I am using requires use of the href...not relevant here.

My jQuery is:

$('a[rel="group"]').on('click', function(e) {
      e.preventDefault();
      var wpurl = $(this).attr("data-wpurl");
      $(this).attr('href', wpurl);
});

I am using e.preventDefault(); to prevent the browser from taking the user to the href. After the data attribute is assigned to the href, how do I then trigger a click? Using trigger('click') and click(); do not work!

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Similar solution, but without the need of calling e.preventDefault()

$('a[rel="group"]').on('click', function(e) {
    e.originalEvent.currentTarget.href = $(this).data('wpurl');
});

from my point of view, this is a more general, cleaner solution, as this will not change the default browser behaviour (e.g.: when the user clicks with the mouse wheel on the link, with Jacks solution no new tab will be opened)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...