How do you assign an event handler to multiple elements in JavaScript?

自作多情 提交于 2019-12-04 05:59:27

问题


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?)?


回答1:


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


来源:https://stackoverflow.com/questions/26351383/how-do-you-assign-an-event-handler-to-multiple-elements-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!