我有一个程序,其中有大量可重用元素,所有这些元素都需要事件侦听器。因此,我需要一种从侦听器获取元素的方法。这是我想在代码中执行的操作:
document.querySelectorAll(".class").forEach(function(el) {
el.addEventListener("click", function(element/*The element that the event listener is assigned to, passed as an argument*/) {
console.log(element) //Print out the element that was clicked in the console
})
})
有什么方法可以在 JavaScript 中复制这个或类似的东西吗?
您可以使用以下命令访问单击的元素this
关键字或循环变量(el
) 在事件回调中。this
通常是首选,因为如果循环变量名称发生更改,您不必担心更改回调中的代码,并且可以避免设置闭包el
,(在适当的情况下)可能会产生意想不到的副作用。
但是,还要注意.querySelectorAll()
返回一个“节点列表”而不是实际的Array
and .forEach()
is an Array
方法。部分浏览器不支持调用.forEach()
在节点列表上,因此您应该将该节点列表转换为正确的Array
以获得最佳兼容性。
// Get the matching nodes in a node list and convert to an Array
let ary = Array.prototype.slice.call(document.querySelectorAll(".test"));
// Now, you can safely use .forEach()
ary.forEach(function(el) {
// Callbacks are passed a reference to the event object that triggered the handler
el.addEventListener("click", function(evt) {
// The this keyword will refer to the element that was clicked
console.log(this.id, el);
});
})
<div class="test" id="div1">Click me</div>
<p class="test" id="p1">No, click me</p>
<div class="test" id="div2">What about me?</div>
<h1 class="test" id="h1">Now, click me</h1>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)