如何为JavaScript中的多个元素分配事件处理程序? [英] How do you assign an event handler to multiple elements in JavaScript?
问题描述
例如,如何将事件处理程序分配给一堆 li
s?
我看到 var li = document.querySelectorAll('li');
。返回类似数组的东西。你只是循环并分配处理程序?我觉得一定要有更好的办法。如果没有,最好的方法是循环遍历数组类的东西(和数组类似的东西叫什么?)?
是的,您应该循环遍历集合并单独分配处理程序。 jQuery也是幕后的。
querySelectorAll
返回一个 NodeList ,它是一个类似数组的对象。
为了循环遍历列表,您可以要么使用循环的:
var list = document.querySelectorAll 'li'),
l = list.length,
li; (var i = 0; i< l; i ++){
li = list.item(i);
// ...
}
或使用 forEach
方法:
[] forEach.call(document.querySelectorAll('li' ),function(li){
// ...
});
I know how to do so with jQuery, and I know how to do so with event delegation. But how do you do so in plain JavaScript?
For example, how do you assign an event handler to a bunch of li
s?
I see that var li = document.querySelectorAll('li');
. Returns an array-like thing. Do you just loop through and assign handlers? I feel like there must be a better way. If not, what's the best way to loop through the array-like thing (and what is the array-like thing called?)?
Yes, you should loop through the collection and assign the handlers individually. jQuery also does this behind the scenes.
querySelectorAll
returns a NodeList which is an array-like object.
For looping through the list, you can either use a for
loop:
var list = document.querySelectorAll('li'),
l = list.length,
li;
for (var i = 0; i < l; i++) {
li = list.item(i);
// ...
}
Or use the forEach
method:
[].forEach.call(document.querySelectorAll('li'), function(li) {
// ...
});
这篇关于如何为JavaScript中的多个元素分配事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!