How to detect Link clicks (text, images, etc) with Javascript?

后端 未结 4 892
盖世英雄少女心
盖世英雄少女心 2020-12-16 00:38

I\'m trying to write a Cross-Browser script that detects when a link is clicked on a page (text link, image, or othwerwise) so that I can show a message or ad (like an inter

4条回答
  •  抹茶落季
    2020-12-16 01:30

    To call a function whenever a link—dynamically added or not—has been clicked, use on()

    $(document).on("click", "a", function() {
        //this == the link that was clicked
        var href = $(this).attr("href");
        alert("You're trying to go to " + href);
    });
    

    If you're using an older version of jQuery, then you would use delegate() (note that the order of selector and event type is switched)

    $(document).delegate("a", "click", function() {
        //this == the link that was clicked
        var href = $(this).attr("href");
        alert("You're trying to go to " + href);
    });
    

提交回复
热议问题