如何在事件侦听器中将元素作为参数传递

fin*_*444 1 html javascript addeventlistener

我有一个程序,其中有大量可重用元素,所有这些元素都需要事件侦听器。因此,我需要一种从侦听器获取元素的方法。这是我想在代码中执行的操作:

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
    })
})
Run Code Online (Sandbox Code Playgroud)

有什么方法可以在 JavaScript 中复制这个或类似的东西吗?

Sco*_*cus 5

您可以使用事件回调中的this关键字或循环变量 ( )访问单击的元素。通常是首选,因为如果循环变量名称发生更改,您不必担心更改回调中的代码,并且它可以避免在 周围设置闭包,这(在正确的情况下)可能会产生意想不到的副作用。elthisel

但是,还要注意.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); 
    });
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)