简体   繁体   中英

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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