addEventListener on NodeList

前端 未结 8 2273
轮回少年
轮回少年 2020-11-30 07:12

Does NodeList support addEventListener. If not what is the best way to add EventListener to all the nodes of the NodeList. Currently I am using the code snippet as show be

8条回答
  •  日久生厌
    2020-11-30 08:02

    The simplest example is to add this functionality to NodeList

    NodeList.prototype.addEventListener = function (event_name, callback, useCapture)
    {
        for (var i = 0; i < this.length; i++)
        {
          this[i].addEventListener(event_name, callback, useCapture);
        }
    };
    

    Now you can do:

    document.querySelectorAll(".my-button").addEventListener("click", function ()
    {
        alert("Hi");
    });
    

    In the same way, you can do a forEach loop

    NodeList.prototype.forEach = function (callback)
    {
        for (var i = 0; i < this.length; i++)
        {
          callback(this[i], i);
        }
    };
    

    Using:

    document.querySelectorAll(".buttons").forEach(function (element, id)
    {
        input.addEventListener("change", function ()
        {
            alert("button: " + id);
        });
    });
    

    EDIT : note that NodeList.prototype.forEach has existed ever since november 2016 in FF. No IE support though

提交回复
热议问题