简体   繁体   English

无法将事件绑定到数组循环中的每个项目

[英]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. 然后,您可以访问图像的srcalt属性。

 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.

相关问题 对数组内的每个项目反应绑定函数 - React bind function to each item inside array 如何遍历一个数组,该数组一次一个地触发数组中每个项目的单击事件 - How to loop through an array that triggers an click event on each item in the array one at a time 将ondblclick事件绑定到列表中的每个项目,并在事件中传递该项目的值 - bind ondblclick event to each item in a list and pass that item's value in the event 遍历每个项目的所有数组项目 - loop through all array items for each item for循环返回数组中一个项的单个字母而不是数组中的每个项 - for loop returning individual letters of one item in array and not each item in the array 遍历数组并为每个项目返回一个`Dropdown.Item`元素 - Loop through the array and return a `Dropdown.Item` element for each item jQuery .each循环执行每个数组项,并在它们之间延迟 - jquery .each loop to execute each array item with a delay between them Zapier-抓钩-JSON数组-遍历数组中的每个项目 - Zapier - Catch Hook - JSON Array - Loop over each item in array 遍历数组,将每个项目添加到对象中,然后将其推入Javascript中的数组 - Loop through an Array, add each item to an object and push it to an array in Javascript 如何使用for循环控制台记录阵列的每个项目? - How to use a for loop to console log each item of an array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM