我有一个程序,它有大量的可重用元素,这些元素都需要一个事件侦听器。正因为如此,我需要一种从监听器获取元素的方法。下面是我想在代码中做的事情:
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中复制这个或类似的东西?
发布于 2018-06-03 05:17:32
可以在事件回调中使用this
关键字或循环变量(el
)来访问单击的元素。this
通常是首选的,因为如果循环变量名发生更改,您不必担心更改回调中的代码,而且它避免了在el
周围设置闭包,这(在适当的情况下)可能会产生意外的副作用。
但也要注意,.querySelectorAll()
返回一个“节点列表”,而不是一个实际的Array
,而.forEach()
是一个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>
https://stackoverflow.com/questions/50661145
复制相似问题