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

时间:2018-06-02 21:04:12

标签: javascript html 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
    })
})

有没有办法在JavaScript中复制这个或类似的东西?

2 个答案:

答案 0 :(得分:3)

您可以在事件回调中使用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>

答案 1 :(得分:2)

在Javascript中,您可以引用外部块/函数中的变量,而不必将它们传递给内部函数:

document.querySelectorAll(".class").forEach(function(el) {
  el.addEventListener("click", function(element) {
    console.log(el);
  })
});

如果触发点击的元素是.class本身(而不是.class的后代之一),您还可以使用event.target来识别它:

document.querySelectorAll(".class").forEach(function(el) {
  el.addEventListener("click", function(event) {
    console.log(event.target);
  })
});

如果 将元素作为参数传递给某个函数而不是访问外部作用域中的元素,我想你可以使用bind

document.querySelectorAll(".class").forEach(function(el) {
  el.addEventListener("click", logElement.bind(null, el));
});
function logElement(element) {
  console.log(element);
}
相关问题