首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在事件侦听器中将元素作为参数传递

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

Stack Overflow用户
提问于 2018-06-03 05:04:12
回答 1查看 5.6K关注 0票数 1

我有一个程序,它有大量的可重用元素,这些元素都需要一个事件侦听器。正因为如此,我需要一种从监听器获取元素的方法。下面是我想在代码中做的事情:

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中复制这个或类似的东西?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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>

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50661145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档