addEventListener on NodeList

依然范特西╮ 提交于 2019-11-26 13:57:09

问题


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 below, is there a better way to do this.

var ar_coins = document.getElementsByClassName('coins');
for(var xx=0;xx < ar_coins.length;xx++)
{
        ar_coins.item(xx).addEventListener('dragstart',handleDragStart,false);
}

回答1:


There is no way to do it without looping through every element. You could, of course, write a function to do it for you.

function addEventListenerList(list, event, fn) {
    for (var i = 0, len = list.length; i < len; i++) {
        list[i].addEventListener(event, fn, false);
    }
}

var ar_coins = document.getElementsByClassName('coins');
addEventListenerList(ar_coins, 'dragstart', handleDragStart); 

or a more specialized version:

function addEventListenerByClass(className, event, fn) {
    var list = document.getElementsByClassName(className);
    for (var i = 0, len = list.length; i < len; i++) {
        list[i].addEventListener(event, fn, false);
    }
}

addEventListenerByClass('coins', 'dragstart', handleDragStart); 

And, though you didn't ask about jQuery, this is the kind of stuff that jQuery is particularly good at:

$('.coins').on('dragstart', handleDragStart);



回答2:


The best I could come up with was this:

const $coins = document.querySelectorAll('.coins')
[...$coins].forEach($coin => $coin.addEventListener('dragstart', handleDragStart));

Note that this uses ES6 features, so please make sure to transpile it first!




回答3:


There actually is a way to do this without a loop:

[].forEach.call(nodeList,function(e){e.addEventListener('click',callback,false)})

And this way is used in one of my one-liner helper libraries - nanoQuery.




回答4:


in es6, you can do a array from nodelist, using Array.from, e.g.

ar_coins = document.getElementsByClassName('coins');
Array
 .from(ar_coins)
 .forEach(addEvent)

function addEvent(element) {
  element.addEventListener('click', callback)
}

or just use arrow functions

Array
  .from(ar_coins)
  .forEach(element => element.addEventListener('click', callback))



回答5:


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




回答6:


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;
    }
});



回答7:


Another solution is to use event-delegation. You just add an eventlistener to the closets parent of the ".coins" and use event.target in the callback to check if the click was really on an element with the class "coins".




回答8:


You could also use prototyping

NodeList.prototype.addEventListener = function (type, callback) {
    this.forEach(function (node) {
        node.addEventListener(type, callback);
    });
};


来源:https://stackoverflow.com/questions/12362256/addeventlistener-on-nodelist

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