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
Javascript Image onload event binding
提问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 i
changes outside of the event listener function, you need a closure.
除此之外,由于i
在事件侦听器函数之外发生了变化,您需要一个闭包。