How to insert image src with while loop in javascript

时间:2016-04-15 11:09:10

标签: javascript

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

1 个答案:

答案 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;
    }
});