如何使用JavaScript在我的字符串中循环我的For循环变量

时间:2018-04-26 11:15:27

标签: javascript

我有大约72个图片名称fun1,fun2......fun72...因此,我只想使用脚本创建72 img标签,而不是编写img标签。但是我无法在这些72图片之间循环,因为我不知道如何在String中调用循环变量。

  

方法1

// For images
let pics = document.getElementById("pics-thumbs");
let divholder = document.createDocumentFragment();
for (let i = 1; i < 73; i++) {
    let img = document.createElement("img");
    img.class = "img-responsive";
    img.src = "images/fun+i.jpg";
    divholder.appendChild(img);
}
pics.appendChild(divholder);
  

方法2

// For images
let pics = document.getElementById("pics-thumbs");
let divholder = document.createDocumentFragment();
for (let i = 1; i < 73; i++) {
    let img = document.createElement("img");
    img.class = "img-responsive";
    img.src = "images/fun" + i ".jpg";
    divholder.appendChild(img);
}
pics.appendChild(divholder);

2 个答案:

答案 0 :(得分:2)

你可以这样做

<强>样本

&#13;
&#13;
let pics = document.getElementById("pics-thumbs"),
  imgArr = [];
for (let i = 1; i < 73; i++) {

  imgArr.push(`<img class="img-responsive" src="images/fun${i}.jpg">`);
}
pics.innerHTML = imgArr.join('<br>')
&#13;
<div id="pics-thumbs"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用

img.src="images/fun" + i + ".jpg";

或者,使用EcmaScript 6,

img.src=`images/fun${i}.jpg`;

它被称为连接