简体   繁体   中英

How can I put values into an object using onload function?

I want to get image size and put it into an object. Here is the code I wrote which doesn't work as I intended.

var images = { a: { src: 'http://aaa/'}, b: {src: 'http://bbb/'}, … };
for (var i in images) {
    var img = new Image();
    img.onload = function() {
        images[i].width = this.width;
        images[i].height = this.height;
    }
    img.src = images[i].src;
}

Your problem is that i will have changed when the callback is called : its value will be the one of end of loop.

A solution is to store images[i] as a variable in an immediately called function. Change your code to

var images = { a: { src: 'http://aaa/'}, b: {src: 'http://bbb/'}, … };
for (var i in images) {
    (function(o){
      var img = new Image();
      img.onload = function() {
        o.width = this.width;
        o.height = this.height;
      };
      img.src = o.src;
    })(images[i]);
}

Demonstration (open the console to see images )

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