Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

for 循环中创建图片并监听 onload 事件失败

问题:通过循环创建图片,并在每个图片加载完成之后执行函数,不过每次都是触发最后一个图片的 onload 事件。
代码:

var src=[
  "http://www.w3school.com.cn/i/site_photoref.jpg",
  "http://www.w3school.com.cn/i/site_photoexa.jpg",
  "http://www.w3school.com.cn/i/site_photoqe.jpg"
]
for(var i=0;i<3;i++){
  var img=new Image();
  img.src=src[i];
  img.onload=function(){
    console.log(img)
  }
}

执行结果是:

<img src="http://www.w3school.com.cn/i/site_photoqe.jpg">
<img src="http://www.w3school.com.cn/i/site_photoqe.jpg">
<img src="http://www.w3school.com.cn/i/site_photoqe.jpg">

我的需求是获得每个图片加载完成之后执行相应的函数,有没有什么好的解决办法?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

js里的事件是异步的,而js异步的最大特点就是得等主线程跑完了才轮的到它执行……在这段程序里,onload只是注册了个事件回调,主程序for还没跑完,它根本没机会切入Event Loop执行事件回调……而等for跑完了,img就一个,所以三遍console.log才打的是一个东西。
而要console.log出三个,一个思路是不要用for,直接用onload驱动就行了。比如我简单写了个递归:

var src=[
    "http://www.w3school.com.cn/i/site_photoref.jpg",
    "http://www.w3school.com.cn/i/site_photoexa.jpg",
    "http://www.w3school.com.cn/i/site_photoqe.jpg"
];

function nextSrc(srcArr, sig){
    var img=new Image();
    img.onload=function(){
        console.log(img.src);
        nextSrc(srcArr, sig + 1);
    }
    img.src=src[sig];
}
nextSrc(src, 0);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...