简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM