addEventListener on NodeList

前端 未结 8 2220
轮回少年
轮回少年 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:04

    I suppose another option would be to define addEventListener on NodeList using Object.defineProperty. That way you can treat the NodeList as you would a single Node.

    As an example, I created a jsfiddle here: http://jsfiddle.net/2LQbe/

    The key point is this:

    Object.defineProperty(NodeList.prototype, "addEventListener", {
        value: function (event, callback, useCapture) {
            useCapture = ( !! useCapture) | false;
            for (var i = 0; i < this.length; ++i) {
                if (this[i] instanceof Node) {
                    this[i].addEventListener(event, callback, useCapture);
                }
            }
            return this;
        }
    });
    

提交回复
热议问题