[英]Could not bind event to each item in array loop
I want to add an event to every image in the document, this is the code: 我想向文档中的每个图像添加一个事件,这是代码:
let images = document.getElementsByTagName("img")
const self = this;
for (var img of images) {
img.onclick = function(e) {
e.stopPropagation();
if (!e.target.src) {
return;
}
self.source = e.target.src;
self.alt = e.target.alt;
}
}
I log all of the images and find that only the last image has the click event. 我记录了所有图像,发现只有最后一个图像具有click事件。 I had tried converting images
into an array and used forEach
methods, which got the same result. 我曾尝试将images
转换成数组并用于forEach
方法,但结果相同。 What's up? 这是怎么回事? By the way, I do that in Vue's mounted
hook method. 顺便说一句,我在Vue的mounted
钩子方法中做到了。
Best way to attach events to multiple DOM elements is to use Event Delegation
. 将事件附加到多个DOM元素的最佳方法是使用Event Delegation
。 You should attach the event
to the parent element and check if the target
element is img or not
. 您应该将event
附加到父元素,并检查target
元素是否为img or not
。 Then you can access the src
and alt
attributes of the image. 然后,您可以访问图像的src
和alt
属性。
var images = document.querySelector('.images'); images.onclick = function(e) { if(e.target.tagName === 'IMG') { console.log(e.target.src +" : " + e.target.alt); } }
<div class="images"> <img alt="1" src="https://randomuser.me/api/portraits/men/83.jpg" /> <img alt="2" src="https://randomuser.me/api/portraits/med/men/83.jpg" /> <img alt="3" src="https://randomuser.me/api/portraits/thumb/men/83.jpg" /> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.