捕获所有< a>点击事件 [英] Capturing all the <a> click event
问题描述
我正在考虑添加一个javascript函数,以捕获html页面内的所有< a>
点击事件。
I am thinking of to add a javascript function to capture all the <a>
click events inside a html page.
所以我正在添加一个全局函数来管理所有的< a>
点击事件,但不要添加onclick到每个(不使用 .onclick =
not attachEvent(onclick ...)
或inline onclick =
) 。我将离开每个< a>
简单到< a href =someurl>
没有碰他们。
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.
我尝试过 window.onclick = function(e){...}
捕获所有点击
如何仅指定< a>
中的点击,并提取< a>
被点击?
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?
限制:我不想使用任何exra库,如jQuery,只是香草
Restriction: I don't want to use any exra libraries like jQuery, just vanilla javascript.
推荐答案
您可以使用window.onclick处理所有点击,然后使用event.target进行过滤
You can handle all click using window.onclick and then filter using event.target
您所问的示例:
<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>
这篇关于捕获所有< a>点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!