[英]Capturing all the <a> click event
I am thinking of to add a javascript function to capture all the <a>
click events inside a html page.我正在考虑添加一个 javascript 函数来捕获 html 页面内的所有
<a>
单击事件。
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=
).因此,我添加了一个全局函数来管理所有
<a>
单击事件,但不向每个事件添加 onclick(既不使用.onclick=
也不使用attachEvent(onclick...)
也不内联onclick=
)。 I will leave each <a>
as simple as <a href="someurl">
within the html without touching them.我会让每个
<a>
像<a href="someurl">
在 html 中一样简单而不触及它们。
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。
Use event delegation :使用事件委托:
document.addEventListener(`click`, e => { const origin = e.target.closest("a"); if (origin) { console.clear(); console.log(`You clicked ${origin.href}`); } });
<div> <a href="#l1">some link</a> <div><a href="#l2"><div><i>some other (nested) link</i></div></a></div> </div>
[ edit 2020/08/20 ] Modernized
[编辑 2020/08/20 ] 现代化
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>
window.onclick = function (e) {
if (e.target.localName == 'a') {
console.log('a tag clicked!');
}
}
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).您将事件委托给窗口然后检查“event.target”是否是链接的想法是一种方法(最好是document.body)。 The trouble here is that it won't work if you click on a child node of your element.
这里的问题是,如果您单击元素的子节点,它将无法工作。 Think:
思考:
<a href="#"><b>I am bold</b></a>
the target
would be the <b>
element, not the link. target
将是<b>
元素,而不是链接。 This means checking for e.target
won't work .这意味着检查
e.target
将不起作用。 So, you would have to crawl up all the dom tree to check if the clicked element is a descendant of a <a>
element.因此,您必须爬上所有 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 转换为数组? 这就是答案。 )
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.您需要考虑到链接可以与其他元素嵌套并希望遍历树回到 'a' 元素。 This works for me:
这对我有用:
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 eg https://jsfiddle.net/hnmdijkema/nn5akf3b/6/参见例如https://jsfiddle.net/hnmdijkema/nn5akf3b/6/
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')
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/
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.
}
}
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.以上将产生相同的结果。
If anybody is looking for the typed version (TypeScript, using Kooilnc's answer), here it is:如果有人正在寻找类型版本(TypeScript,使用 Kooilnc 的答案),这里是:
document.addEventListener("click", (e: Event) => {
if(!e.target) { return; }
if(!(e.target instanceof Element)) { return; }
const origin = e.target.closest("a");
if(!origin || !origin.href) { return; }
console.log(`You clicked ${origin.href}`);
});
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.希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.