关于图像变化的故障

时间:2015-08-11 18:39:13

标签: jquery

在大多数情况下,我的图像会发生变化,但很多时候它会发生变化,图像会保持不变。

$(window).ready(function () {
  //variable images = array
  var images = [];

  var loop, i = 0;

  //set array images to index
  images[0] = "design/img/NYC.jpg";
  images[1] = "design/img/meandning.jpg";

  $('#imgz').load(function () {
      var image = this;
      loop = setInterval(function () {
          if (i < images.length - 1) {
              i++;
              $(image).attr('src', images[i]);
          } else {
              i = 0;
              $(image).attr('src', images[i]);
          }
      }, 2000);

  })
});

1 个答案:

答案 0 :(得分:2)

每次更改.load时,src事件都会触发,这意味着每次都会创建新的setInterval。您可以使用.one()仅将事件绑定到第一个图像加载...

&#13;
&#13;
//variable images = array
  var images = [];

  var loop, i = 0;

  //set array images to index
  images[0] = "http://placehold.it/400x400?text=Slide%201";
  images[1] = "http://placehold.it/400x400?text=Slide%202";

  $('#imgz').one('load',function () {
      var image = this;
      loop = setInterval(function () {
          if (i < images.length - 1) {
              i++;
              $(image).attr('src', images[i]);
          } else {
              i = 0;
              $(image).attr('src', images[i]);
          }

          //show.html(i);
      }, 2000);

  })
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<img id="imgz" src="http://placehold.it/400x400?text=Slide%200">
&#13;
&#13;
&#13;

&#34;故障&#34;您看到的是由多个setInterval同时更改src引起的。