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
1.1k views
in Technique[技术] by (71.8m points)

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

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 interstitial) and then direct the visitor to the originally clicked destination url.

The script has to work from 3rd party sites (where the owner installs the script tags on his or her site).

How can I accomplish this using javascript?

Do I use an event listener? Do I iterate through all link objects? Or something else?

My javascript skills are newbie/intermediate so detailed examples/explanations are greatly appreciated.

I've started off using the event listener here, but so far I'm detecting ALL clicks on the page: addEventListener Code Snippet Translation and Usage for cross-browser detectioin

I'll consider a JQuery alternative, but I just don't know how it'll work on 3rd party site if that site doesn't have the JQuery library.

Thanks all.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...