循环遍历数组和打印元素到页面

时间:2018-01-21 20:24:55

标签: javascript jquery

我正在尝试遍历array并将图像显示在屏幕上。这只显示我的最后一个,但是当我控制日志crystalImg[i]时,我得到了所有图像。我不确定我在做什么,它只显示最后一张图片。

var crystalImg = ["assets/images/blue.png",
"assets/images/pink.png",
"assets/images/purple.png",
"assets/images/red.png"];

for (i = 0; i < crystalImg.length; i++) {
  $("#jewels").html("<img src='" + crystalImg[i] + "'>");
  console.log(crystalImg[i]);
}

1 个答案:

答案 0 :(得分:0)

您要替换整个HTML,请改用append函数。

&#13;
&#13;
var crystalImg = ["assets/images/blue.png", "assets/images/pink.png", 
"assets/images/purple.png", "assets/images/red.png"];

for (i = 0; i < crystalImg.length; i++) {
    $("#jewels").append("<img src='" + crystalImg[i] + "'>");
    console.log(crystalImg[i]);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='jewels'>
</div>
&#13;
&#13;
&#13;