如何将事件侦听器添加到html集合中的每个类? [英] How to add event listener to each class in an html collection?

查看:103
本文介绍了如何将事件侦听器添加到html集合中的每个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过元素"类获取所有元素,并向每个元素添加一个事件侦听器.但是,getElementsByClassName()返回和html集合.当我使用.length()时,它等于零.我如何遍历此集合以便将事件侦听器添加到此类中的每个元素?有没有办法将此html集合转换为数组? 这是我到目前为止的内容:

I'm attempting to get all elements by the class of 'element' and adding an event listener to each of them. however, getElementsByClassName() returns and html collection. When I use .length() it equals zero. how do I iterate through this collection in order to add event listener to each element in this class? is there a way to convert this html collection into an array? here's what i have so far:

var tableElements = document.getElementsByClassName("element");
console.log(tableElements);
console.log(tableElements.length);

for(var i=0;i<tableElements.length;i++){
   tableElements[i].addEventListener("click", dispElementData(this));
} //doesnt work

推荐答案

对不起!我上面的代码工作正常!原来我的JS代码是在DOM完成加载之前执行的.感谢您的帮助.解决方案是添加一个evt侦听器文档对象,然后在函数完全加载后调用该函数:

Sorry! My code above works fine! Turns out that my JS code was executing before the DOM was done loading. Thanks for the the help. The solution was to add an evt listener document object and then call the function once it was completely loaded:

document.addEventListener("DOMContentLoaded", function(){
                  var tableElements = document.getElementsByClassName("element");  
             for(var i=0;i<tableElements.length;i++){ 
                tableElements[i].addEventListener("click", dispElementData(this)); 
              }
})

这篇关于如何将事件侦听器添加到html集合中的每个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆