且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为JavaScript中的多个元素分配事件处理程序?

更新时间:2023-02-09 14:10:35

是的,您应该循环遍历集合并单独分配处理程序。 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 lis?

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) {
    // ...
});