javascript - 图像未加载并插入数组(javascript)

标签 javascript arrays object loops

我想通过循环遍历名为 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
}

最佳答案

这是因为您的 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
}

关于javascript - 图像未加载并插入数组(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990315/

相关文章:

javascript - 父 DIV 的 CSS 干扰 SVG 动画

javascript 电子邮件换行符

javascript - 如何在 Angular 6 中显示带有变化字符串的嵌套 JSON 对象

javascript - 在没有 ng-repeat 的情况下使用 Angular ng-if?

c++ - cconstructor 中的迭代器 - vector 和数组

java - 打印 ArrayList 中的对象

javascript - 如何使 Transcrypt 编译为对象而不是字典?

javascript - 无法为 apexcharts 获取正确格式的数据

java - 在并行数组中搜索匹配值

c# - 有条件地创建不同类的对象