简体   繁体   中英

Pass the destination URL of clicked link to javascript/jQuery

After reading this Q&A I was able to pass the URL of a specific div to jQuery upon clicking the link. However, I have multiple links of the page and I want to pass their individual href values to jQuery upon clicking. Right now the code selects all links on the page:

jQuery(document).ready(function(){
  jQuery(".view-frontpage a").click(function (event) {
    href = $('.view-frontpage a').attr('href');
    event.preventDefault();
    alert(href);
   });
});

The result of this currently is that it pops up a dialog displaying the href property of the first link on the page, regardless of which link is clicked. How do I change this to give me the href of the link that has just been clicked?

This should work. Change:

href = $('.view-frontpage a').attr('href');

To:

href = $(this).attr('href');

First, it's a good idea to use event delegation so you don't actually create a handler for every link on your page.

In your case, jQuery binds this inside your click handler to the click event target (the element that's been clicked on), so you need to do href = $(this).attr('href'); to get the href of the link you need.

Here is the full code using the new jQuery on() function (available since 1.7)

$(document).on('click', '.view-frontpage a', function(e) {
    alert($(this).attr('href'));

    e.preventDefault();
    return false;
});​​​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM