简体   繁体   English

在集合上添加事件监听器

[英]adding event listener on collection

if I have a collection that has the same class, how can I add an onclick event listener without effecting each item with that class. 如果我有一个具有相同类的集合,那么如何在不影响该类的每个项目的情况下添加onclick事件侦听器。

<div class = "overlay">etc. etc.</div>
<div class = "overlay">etc. etc.</div>
<div class = "overlay">etc. etc.</div>
<div class = "overlay">etc. etc.</div>

I'd want to run the following but only effect the one I click...not all of them with the classname 'overlay': 我想执行以下操作,但只影响我单击的操作……不是所有的类名都为“ overlay”:

x = document.getElementsByClassName("overlay")
x.addEventListener("click", function() { this.addClassName("hide"); } );

Try it: 试试吧:

x = document.getElementsByClassName("overlay");
for(var i = 0; i < x.length; i++){
    x[i].addEventListener("click", function() { this.classList.add("hide"); })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM