简体   繁体   中英

How do I listen on all array items?

I am collecting all images elements from the document var listen = document.getElementsByTagName('img'); which results in an array. Now I have to specify listen[0] , listen[1] , listen[2] , listen[3] etc to listen for events on a element from this array. The question is is there any way to just do something like listen[any item from this array] , or a function. Just to don't have to specify every element to listen on manually.

Example

Now I have to do something like this, for every array item: listen[3].click = function() {};

Depending on what it is exactly what you want and what the DOM looks like you may want to use an event listener higher up the DOM tree somewhere instead of create a lot of listeners:

document.addEventListener('click', function(e) {
    if (e.target.nodeName !== 'IMG') {
        return;
    }

    alert('img clicked');
});

Demo: http://jsfiddle.net/APSMT/1/

Note that I have attached the event listener to document , but if you can make it more specific you should

With a reasonable new browser you can use Array.forEach :

[].forEach.call(document.getElementsByTagName('img'), function (img) {
    el.addEventListener('click', callback);
});

Or "old skool" (and maybe even better readable):

var imgs = document.getElementsByTagName('img');
for (var i = 0, len = imgs.length; i < len; ++i) {
    imgs[i].addEventListener('click', callback);
}

Reading the HTMLCollection.length only once can give a speed-up. It will never be slower.

You should not create a Function object for every iteration:

// Don't
for (...) {
    img[i].onclick = function () { ... }
}

// Do
function onclick () {
     // `this` will be img[i]
}
for (...) {
    img[i].onclick = onclick;
}

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