如何使用 Javascript 检测链接点击(文本、图像等)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8451771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:29:45  来源:igfitidea点击:

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

javascriptjquerycross-browserevent-listener

提问by C King

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 tagson his or her site).

该脚本必须在 3rd 方站点(所有者在他或她的站点上安装脚本标签)上运行。

How can I accomplish this using javascript?

如何使用 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.

我的 javascript 技能是新手/中级,因此非常感谢详细的示例/解释。

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

我已经开始在这里使用事件侦听器,但到目前为止我正在检测页面上的所有点击: addEventListener 代码片段翻译和跨浏览器检测的使用

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.

我会考虑使用 JQuery 替代方案,但我只是不知道如果该站点没有 JQuery 库,它将如何在 3rd 方站点上工作。

Thanks all.

谢谢大家。

采纳答案by David says reinstate Monica

I thought I'd try a non-jQuery (and non-other-library solution too, just for...well, filling a few minutes):

我想我会尝试一个非 jQuery(以及非其他库解决方案,只是为了......好吧,填补几分钟):

function clickOrigin(e){
    var target = e.target;
    var tag = [];
    tag.tagType = target.tagName.toLowerCase();
    tag.tagClass = target.className.split(' ');
    tag.id = target.id;
    tag.parent = target.parentNode;

    return tag;
}

var tagsToIdentify = ['img','a'];

document.body.onclick = function(e){
    elem = clickOrigin(e);

    for (i=0;i<tagsToIdentify.length;i++){
        if (elem.tagType == tagsToIdentify[i]){
            console.log('You\'ve clicked a monitored tag (' + elem.tagType + ', in this case).');
            return false; // or do something else.
        }
    }
};

JS Fiddle demo.

JS小提琴演示

Amended the above, to detect imgelements nested within an aelement (which I thinkis what you're wanting having re-read your question):

修改了上述内容,以检测img嵌套在元素中的a元素(我认为这是您想要重新阅读您的问题的内容):

function clickOrigin(e){
    var target = e.target;
    var tag = [];
    tag.tagType = target.tagName.toLowerCase();
    tag.tagClass = target.className.split(' ');
    tag.id = target.id;
    tag.parent = target.parentNode.tagName.toLowerCase();

    return tag;
}

var tagsToIdentify = ['img','a'];

document.body.onclick = function(e){
    elem = clickOrigin(e);

    for (i=0;i<tagsToIdentify.length;i++){
        if (elem.tagType == tagsToIdentify[i] && elem.parent == 'a'){
            console.log('You\'ve clicked a monitored tag (' + elem.tagType + ', in this case and one inside an "a" element, no less!).');
            return false; // or do something else.
        }
        else if (elem.tagType == tagsToIdentify[i]){
            console.log('You\'ve clicked a monitored tag (' + elem.tagType + ', in this case).');
            return false; // or do something else.
        }
    }
};

JS Fiddle demo.

JS小提琴演示

回答by Adam Rackis

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

要在链接(动态添加或未动态添加)被点击时调用函数,请使用 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)

如果您使用的是旧版本的 jQuery,那么您将使用delegate()(注意选择器和事件类型的顺序已切换)

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

回答by Barkermn01

i use this that way it only affects the a tags with links in them,

我这样使用它只会影响带有链接的 a 标签,

(function($){
$("a[href!='']").each(function(){
    $(this).click(function(){
    var href = $(this).attr("href")
    })
});
})(jQuery);

But on this note you say your wanting people to use this on 3rd party web sites so they might not have jQuery so you might need this check in the top of your file but then you will need to include your file after use the same code but check for your object or a function name

但是在此说明中,您说您希望人们在 3rd 方网站上使用它,因此他们可能没有 jQuery,因此您可能需要在文件顶部进行此检查,但是在使用相同的代码后,您将需要包含您的文件,但是检查您的对象或函数名称

if(typeof(jQuery) == undefined){
    var head = docuent.getElementsByTagName('head')[0];
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "http://yourserver.url/jquery.js");
    head.appendChild(script);
}

回答by user1090520

This is roughly how to do it withoutuse of jQuery:

这大致是如何在使用 jQuery 的情况下做到的:

<html>

    <head>
            <script type="text/javascript">
            window.onload = function() {
              var observed = document.getElementsByTagName('a');

              for (var i = 0; i < observed.length; i++) {
                observed[i].addEventListener('click', function (e) {
                   var e=window.event||e;

                   alert('Clicked ' + e.srcElement.innerText);

                   if (e.preventDefault) { e.preventDefault() } else { e.returnValue=false }
                }, false);
              }
            }
            </script>
    </head>


    <body>

            <a href="">foo</a>
            <a href="">bar</a>

    </body>
</html>