【问题标题】:Images not being loaded and pushed into array (javascript)图像未加载并推入数组(javascript)
【发布时间】:2013-02-20 21:30:58
【问题描述】:

我想通过循环访问一个名为 GameImages 的对象变量来为我的图像编写所有 onload 函数。当我在 chrome 中查看开发人员控制台时,我不确定为什么没有加载图像。 for 循环是否会中断图像的加载?如何循环加载图像而不是编写每个 onload 函数?

var i = 1; //set increment variable

var GameImages = { //object to hold each image

    game1 : new Image(),
    game2 : new Image(),
    game3 : new Image(),
    game4 : new Image(),
    game5 : new Image(),

};

for(gameImage in GameImages) { //loop through each image

    gameImage.onload = function () { //set the onload function for the current image

        gamePosters.push(gameImage);
        console.log(gamePosters.length); //print out the new size of the gamePosters array

    };

    //give source of image. (my images are named game1.jpg, game2.jpg, etc.)
    gameImage.src = "images/assets/posters/games/game" + i + ".jpg";

    i += 1; //increment i
}

【问题讨论】:

    标签: javascript arrays object loops


    【解决方案1】:

    这是因为您的 for (gameImage in GameImages) 循环正在遍历您的每个 GameImage 对象的属性(即,gameImage 首先是“game1”,然后是“game2”,等等)。将您的代码更改为:

    for (game in GameImages) {
    
       var gameImage = GameImages[game]; // This will get your actual Image
       gameImage.onload = function () { 
    
           gamePosters.push(gameImage);
           console.log(gamePosters.length); 
    
       };
    
       //give source of image. (my images are named game1.jpg, game2.jpg, etc.)
       gameImage.src = "images/assets/posters/games/game" + i + ".jpg";
    
       i += 1; //increment i
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 2013-06-11
      • 2013-03-25
      • 2020-11-03
      • 1970-01-01
      • 2017-03-28
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多