我有大约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);
答案 0 :(得分:2)
你可以这样做
<强>样本强>
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;
答案 1 :(得分:1)
使用
img.src="images/fun" + i + ".jpg";
或者,使用EcmaScript 6,
img.src=`images/fun${i}.jpg`;
它被称为连接。