I want to insert image src with while loop in javascript
$(document).ready(function(){
var i=1;
while(i <= 40)
{
document.getElementByClassName("fruit").src += "path" + i + ".png";
i+=1;
}
});
<img class="img-responsive" src="path/1.png" />
<img class="img-responsive" src="path/2.png" />
<img class="img-responsive" src="path/3.png" />
...
<img class="img-responsive" src="path/40.png" />
How to create this series with javascript
答案 0 :(得分:0)
最好首先查看具有类名的元素集合,而不是在每次遍历while循环时评估集合。
$(document).ready(function(){
var i = 0;
var elementCollection = document.getElementsByClassName('img-responsive');
var max_i = elementCollection.length;
while(i < 40 && i < max_i) {
elementCollection[i].src = "path/" + i + ".png";
i+=1;
}
});