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

前端 未结 1 1549
感情败类
感情败类 2021-01-26 02:56

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

相关标签:
1条回答
  • 2021-01-26 03:30

    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) {
        // ...
    });
    
    0 讨论(0)
提交回复
热议问题