NodeList上的addEventListener [英] addEventListener on NodeList
本文介绍了NodeList上的addEventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
NodeList是否支持addEventListener。如果不是,将EventListener添加到NodeList的所有节点的最佳方法是什么。目前我使用的代码片段如下所示,是否有更好的方法。
Does NodeList support addEventListener. If not what is the best way to add EventListener to all the nodes of the NodeList. Currently I am using the code snippet as show below, is there a better way to do this.
var ar_coins = document.getElementsByClassName('coins');
for(var xx=0;xx < ar_coins.length;xx++)
{
ar_coins.item(xx).addEventListener('dragstart',handleDragStart,false);
}
推荐答案
没办法办它没有遍历每个元素。当然,您可以编写一个函数来为您完成。
There is no way to do it without looping through every element. You could, of course, write a function to do it for you.
function addEventListenerList(list, event, fn) {
for (var i = 0, len = list.length; i < len; i++) {
list[i].addEventListener(event, fn, false);
}
}
var ar_coins = document.getElementsByClassName('coins');
addEventListenerList(ar_coins, 'dragstart', handleDragStart);
或更专业的版本:
function addEventListenerByClass(className, event, fn) {
var list = document.getElementsByClassName(className);
for (var i = 0, len = list.length; i < len; i++) {
list[i].addEventListener(event, fn, false);
}
}
addEventListenerByClass('coins', 'dragstart', handleDragStart);
而且,虽然你没有问过jQuery,但这是jQuery特别重要的东西擅长:
And, though you didn't ask about jQuery, this is the kind of stuff that jQuery is particularly good at:
$('.coins').on('dragstart', handleDragStart);
这篇关于NodeList上的addEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文