简体   繁体   English

Javascript Image onload事件绑定

[英]Javascript Image onload event binding

So I have this piece of code that loops through an array and load images and notify when the images is loaded. 所以我有这段代码循环遍历数组并加载图像并在加载图像时通知。

for (var i = 0; i < arr.length; i++) {                
    var imageObj = new Image();
    imageObj.src = url[i];
    imageObj.onload= (function(i){
                return function(){
                    console.log(i, 'loaded');
                }
            })(i);

}

It works fine. 它工作正常。 However if I try to do this it won't work 但是,如果我尝试这样做,它将无法正常工作

imageObj.addEventListener('onload', function(
    console.log(i, 'loaded');
}, false);

What is the problem? 问题是什么? And is there any way for me to avoid using closure in this case? 在这种情况下,我有什么方法可以避免使用闭包吗?

One part of the problem: The event is not called onload , but load . 问题的一部分:事件不是onload ,而是load

imageObj.addEventListener('load', function() { /* ... */ }, false);

Other than that, since i changes outside of the event listener function, you need a closure. 除此之外,因为i在事件监听器函数之外更改,您需要一个闭包。

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

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