简体   繁体   English

我可以在带有img元素的for循环中使用addEventListener

[英]can I use addEventListener in a for loop with img elements

I understand that addEventListener isn't IE friendly, but I'm curious about this approach in general. 我知道addEventListener不是IE友好的,但我对此总体上很好奇。

I'm trying to use an 'onload' addEventListener with imgs in a loop, other than my function not firing it looks like the event listener is only being added to the first element. 我正在尝试在循环中使用带有imgs的“ onload” addEventListener,而不是我的函数未触发它,似乎事件侦听器仅被添加到第一个元素。 The images paths are coming from some PHP and I'm trying to take the onload out of my HTML. 图片路径来自某些PHP,我正在尝试从HTML中删除onload。

Originally I had it like this (excerpt of HTML from a PHP while): 最初我是这样的(来自PHP的HTML摘录):

<img 
onLoad="SLIDESHOW.crkarchProject.onImageLoad(<?php echo $rowSlideImage[1]; ?>)" 
id="<?php echo $rowSlideImage[1]; ?>" 
src="./slideshow_images/<?php echo $rowSlideImage[2]; ?>" 
alt="<?php echo $rowSlideImage[3]; ?>"/>

What I'd like to do is use addEventListener in my loop for each image. 我想要做的是在每个图像的循环中使用addEventListener。 This is the code excerpt I'm working on now: 这是我现在正在处理的代码摘录:

// get the images and how many
photos = slideshow.getElementsByTagName("img");
totalImageCount =  photos.length;
for (i = 0; i < totalImageCount; i += 1) {
    var elem = photos[i];
    elem.addEventListener('onload', doIt, false);
}

function doIt() {
    console.log("YO!");
}

Is my approach all wrong? 我的方法全错了吗? Is that var elem a bad idea in the for loop? 那个var elem在for循环中是个坏主意吗? I've also tried: 我也尝试过:

// also tried this in the loop
photos[i].addEventListener('onload', doIt, false);

Should I just avoid addEventListener all together (b/c of the IE thing). 我应该避免一起使用addEventListener(IE的b / c)。 I do see the doIt firing when I use elem.onload directly in the loop. 当我直接在循环中使用elem.onload时,确实看到了doIt触发。

// this will fire the doIt!
elem.onload = doIt();

Thanks! 谢谢!

Change to 改成

 elem.addEventListener('load', doIt, false);

You got the event type wrong. 您错误输入了事件类型。 Yours refers to attachEvent . 您指的是attachEvent For a full list of event types have a look at here . 有关事件类型的完整列表,请参见此处

I recommend to use JQuery, it's compatible with almost all browsers, and very easy to write what you are trying to do: 我建议使用JQuery,它与几乎所有浏览器兼容,并且非常容易编写您要执行的操作:

$('img').load(function() {
  // Handler for .load() called.
  console.log("YO!");
});

However, your code seems to be right. 但是,您的代码似乎是正确的。

If you're only attaching one listener (which is the vast majority of cases), the simplest way is to just add it to the appropriate property: 如果您仅附加一个侦听器(大多数情况下),最简单的方法是将其添加到适当的属性中:

var i = document.images.length;
while (i--) {
  document.images[i].onload = doIt;
}

which will work in every browser that supports scripting. 在所有支持脚本的浏览器中均可使用。

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

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