简体   繁体   English

如何监听所有数组项?

[英]How do I listen on all array items?

I am collecting all images elements from the document var listen = document.getElementsByTagName('img');我正在收集文档中的所有图像元素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.现在我必须指定listen[0]listen[1]listen[2]listen[3]等来监听这个数组元素上的事件。 The question is is there any way to just do something like listen[any item from this array] , or a function.问题是有什么方法可以做一些类似listen[any item from this array]或函数的事情。 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() {};现在我必须为每个数组项做这样的事情: 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:根据您想要的内容以及 DOM 的外观,您可能希望在 DOM 树的更高位置使用事件侦听器,而不是创建大量侦听器:

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

    alert('img clicked');
});

Demo: http://jsfiddle.net/APSMT/1/演示: 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请注意,我已将事件侦听器附加到document ,但如果您可以使其更具体,则应该

With a reasonable new browser you can use Array.forEach :使用合理的新浏览器,您可以使用Array.forEach

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

Or "old skool" (and maybe even better readable):或“老 skool”(甚至可能更好读):

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.仅读取一次HTMLCollection.length可以加快速度。 It will never be slower.它永远不会更慢。

You should not create a Function object for every iteration:您不应该为每次迭代都创建一个 Function 对象:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM