如何为JavaScript中的多个元素分配事件处理程序? [英] How do you assign an event handler to multiple elements in JavaScript?

查看:139
本文介绍了如何为JavaScript中的多个元素分配事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用jQuery,我知道如何通过事件委托来做到这一点。但是,如何在纯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 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) {
    // ...
});

这篇关于如何为JavaScript中的多个元素分配事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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