且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript Image onload事件绑定

更新时间:2023-12-04 22:24:46

问题的一部分:这个事件不叫 onload ,但是 load

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

除此之外,由于 i 在事件侦听器函数外发生更改,因此需要关闭。


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.

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

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