Javascript Image onload 事件绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10121797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:56:30  来源:igfitidea点击:

Javascript Image onload event binding

javascripthtmljavascript-events

提问by Ethan

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?

问题是什么?在这种情况下,我有什么办法可以避免使用闭包吗?

回答by Anders Tornblad

One part of the problem: The event is not called onload, but load.

问题的一部分:事件不是调用onload,而是load

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

Other than that, since ichanges outside of the event listener function, you need a closure.

除此之外,由于i在事件侦听器函数之外发生了变化,您需要一个闭包。