Javascript 捕获所有 <a> 点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12551920/
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-08-23 10:41:10  来源:igfitidea点击:

Capturing all the <a> click event

javascripteventscapture

提问by user1589188

I am thinking of to add a javascript function to capture all the <a>click events inside a html page.

我正在考虑添加一个 javascript 函数来捕获<a>html 页面内的所有点击事件。

So I am adding a global function that governs all the <a>click events, but not adding onclick to each (neither using .onclick=nor attachEvent(onclick...)nor inline onclick=). I will leave each <a>as simple as <a href="someurl">within the html without touching them.

所以我增加了全球功能管理所有的<a>点击事件,但不增加的onclick每个(既不使用.onclick=也不是attachEvent(onclick...)也不是内联onclick=)。我将把每一个都保留在 html 中<a>一样简单<a href="someurl">而不触及它们。

I tried window.onclick = function (e) {...}but that just captures all the clicks How do I specify only the clicks on <a>and to extract the links inside <a>that is being clicked?

我试过了,window.onclick = function (e) {...}但这只是捕获所有点击我如何只指定点击<a>并提取<a>被点击的内部链接?

Restriction: I don't want to use any exra libraries like jQuery, just vanilla javascript.

限制:我不想使用任何像 jQuery 这样的 exra 库,只想使用 vanilla javascript。

回答by KooiInc

Use something like:

使用类似的东西:

document.body.onclick = function(e){
  e = e || event;
  var from = findParent('a',e.target || e.srcElement);
  if (from){
     /* it's a link, actions here */
  }
}
//find first parent with tagName [tagname]
function findParent(tagname,el){
  while (el){
    if ((el.nodeName || el.tagName).toLowerCase()===tagname.toLowerCase()){
      return el;
    }
    el = el.parentNode;
  }
  return null;
}

The technique is called event delegation

该技术称为事件委托

[edit] added a function to enable a clickhandler for links width nested html-elements, like:
<a ...><b><i>link text</i></b></a>

[编辑] 添加了一个功能来为链接宽度嵌套的 html 元素启用点击处理程序,例如:
<a ...><b><i>link text</i></b></a>

回答by Artur Udod

You can handle all click using window.onclick and then filter using event.target

您可以使用 window.onclick 处理所有点击,然后使用 event.target 进行过滤

Example as you asked:

你问的例子:

<html>
<head>
<script type="text/javascript">
window.onclick = function(e) { alert(e.target);};
</script>
</head>
<body>
<a href="http://google.com">google</a>
<a href="http://yahoo.com">yahoo</a>
<a href="http://facebook.com">facebook</a>
</body>
</html>

回答by xdazz

?window.onclick = function (e) {
    if (e.target.localName == 'a') {
        console.log('a tag clicked!');
    }
}?

The working demo.

工作演示。

回答by Hans Dijkema

You need to take into account that a link can be nested with other elements and want to traverse the tree back to the 'a' element. This works for me:

您需要考虑到链接可以与其他元素嵌套并希望遍历树回到 'a' 元素。这对我有用:

window.onclick = function(e) {
  var node = e.target;
  while (node != undefined && node.localName != 'a') {
    node = node.parentNode;
  }
  if (node != undefined) {
    console.log(node.href);
    /* Your link handler here */
    return false;  // stop handling the click
  } else {
    return true;  // handle other clicks
  }
}

See e.g. https://jsfiddle.net/hnmdijkema/nn5akf3b/6/

参见例如https://jsfiddle.net/hnmdijkema/nn5akf3b/6/

回答by Roman

your idea to delegate the event to the window and then check if the "event.target" is a link, is one way to go (better would be document.body). The trouble here is that it won't work if you click on a child node of your element. Think:

您将事件委托给窗口然后检查“event.target”是否是链接的想法是一种方法(最好是document.body)。这里的问题是,如果您单击元素的子节点,它将无法工作。思考:

<a href="#"><b>I am bold</b></a>

the targetwould be the <b>element, not the link. This means checking for e.targetwon't work. So, you would have to crawl up all the dom tree to check if the clicked element is a descendant of a <a>element.

thetarget将是<b>元素,而不是链接。这意味着检查e.target将不起作用。因此,您必须爬上所有 dom 树以检查被单击的元素是否是某个元素的后代<a>

Another method that requires less computation on every click, but costs more to initialize would be to get all <a>tags and attach your event in a loop:

另一种每次点击需要较少计算但初始化成本更高的方法是获取所有<a>标签并将您的事件附加到循环中:

var links = Array.prototype.slice.call(
    document.getElementsByTagName('a')
);

var count = links.length;
for(var i = 0; i < count; i++) {
    links[i].addEventListener('click', function(e) {
        //your code here
    });
}

(PS: why do I convert the HTMLCollection to array? here's the answer.)

(PS:为什么我要将 HTMLCollection 转换为数组?这就是答案。

回答by FLCL

Try jQuery and

尝试 jQuery 和

$('a').click(function(event) { *your code here* });

In this function you can extract href value in this way:

在此函数中,您可以通过以下方式提取 href 值:

$(this).attr('href')

回答by Akshat Mittal

You can also try using this:

你也可以尝试使用这个:

var forEach = Array.prototype.forEach;
var links = document.getElementsByTagName('a');
forEach.call(links, function (link) {
    link.onclick = function () {
        console.log('Clicked');
    }

});

It works, I just tested!

它有效,我刚刚测试过!

Working Demo: http://jsfiddle.net/CR7Sz/

工作演示:http: //jsfiddle.net/CR7Sz/

Somewhere in comments you mentioned you want to get the 'href' value you can do that with this:

在您提到的评论中的某个地方,您想获得“href”值,您可以这样做:

var forEach = Array.prototype.forEach;
var links = document.getElementsByTagName('a');
forEach.call(links, function (link) {
    link.onclick = function () {
        console.log(link.href); //use link.href for the value
    }

});

Demo: http://jsfiddle.net/CR7Sz/1/

演示:http: //jsfiddle.net/CR7Sz/1/

回答by Micha?Kraków

Some accepted answers dont work with nested elements like: <a href="..."><font><u>link</u></font></a>

一些接受的答案不适用于嵌套元素,例如: <a href="..."><font><u>link</u></font></a>

There is a basic solution for most cases: ```

大多数情况下有一个基本的解决方案:```

var links = document.getElementsByTagName('a');
for(var i in links)
{
    links[i].onclick = function(e){
        e.preventDefault();
        var href = this.href;
        // ... do what you need here.
    }
}

回答by Vishal Srinivasan

I guess this simple code will work with jquery.

我想这个简单的代码将适用于 jquery。

 $("a").click(function(){
    alert($(this).attr('href'));
});

Without JQuery:

没有 JQuery:

window.onclick = function(e) { 
if(e.target.localName=='a')
    alert(e.target);
};

The above will produce the same result.

以上将产生相同的结果。

回答by Kivylius

Very simple :

很简单 :

document.getElementById("YOUR_ID").onclick = function (e) {...} 

The selector is what you want to select so lets say you have button called

选择器是您要选择的内容,因此可以说您有一个名为的按钮

<a href="#" id="button1">Button1</a>

The code to capure this is:

捕获这个的代码是:

document.getElementById("button1").onclick = function (e) { alert('button1 clicked'); }

Hope that helps.

希望有帮助。