我在一页上放了很多照片:
<img src="1.gif" /><br>
<img src="2.gif" /><br>
<img src="3.gif" /><br>
<img src="4.gif" /><br>
<img src="5.gif" /><br>
<img src="6.gif" /><br>
<img src="7.gif" /><br>
<img src="8.gif" /><br>
<img src="9.gif" /><br>
<img src="10.gif" /><br>
<img src="11.gif" /><br>
<img src="12.gif" /><br>
<img src="13.gif" /><br>
<img src="14.gif" /><br>
<img src="15.gif" /><br>
<img src="16.gif" /><br>
<img src="17.gif" /><br>
<img src="18.gif" /><br>
<img src="19.gif" /><br>
<img src="20.gif" /><br>
<img src="21.gif" /><br>
<img src="22.gif" /><br>
<img src="23.gif" /><br>
<img src="24.gif" /><br>
<img src="25.gif" /><br>
还有其他办法吗?就像javascript中的for循环一样?
我尝试使用javascript for循环(i +“。gif”)。
答案 0 :(得分:6)
var imagesCount = 25;
// Create a fragment to collect the images
var fragment = document.createDocumentFragment();
for (var i = 1; i <= imagesCount; i++) {
var img = document.createElement('img');
// give the image it's src based on i
img.src = i + ".gif";
fragment.appendChild(img);
}
// Insert the images in body
document.body.appendChild(fragment);
答案 1 :(得分:0)
我希望这会有所帮助,请看这个完整的例子:
var i;
var generatedImages = "";
for (i = 1; i <= 25; i++) {
var srcString = i + ".gif";
generatedImages += "<img src=" + srcString + " /><br>";
}
document.getElementById("demo").innerHTML = generatedImages;
&#13;
<!DOCTYPE html>
<html>
<body>
<div id="demo"></div>
<script>
</script>
</body>
</html>
&#13;
答案 2 :(得分:0)
<强> HTML 强>
<div id="images-container"></div>
<强> JS 强>
var imagesData = [
{src: "demo.gif", alt: "Demo"},
...
];
var imagesContainer = document.getElementById("images-container");
imagesData.forEach(function (data) {
var img = new Image();
img.src = data.src;
img.alt = data.alt;
imagesContainer.appendChild(img);
});