JavaScript Image onload事件绑定 [英] Javascript Image onload event binding

查看:90
本文介绍了JavaScript Image onload事件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

所以我有这段代码循环访问一个数组并加载图像并通知图像何时加载。 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');
}
})(一世);

}

工作正常。但是,如果我尝试这样做,它将无法正常工作

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

是这样的问题?有没有什么办法可以避免在这种情况下使用闭包?

解决方案

问题的一部分:这个事件不叫 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.

这篇关于JavaScript Image onload事件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆