在大多数情况下,我的图像会发生变化,但很多时候它会发生变化,图像会保持不变。
$(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);
})
});
答案 0 :(得分:2)
每次更改.load
时,src
事件都会触发,这意味着每次都会创建新的setInterval
。您可以使用.one()
仅将事件绑定到第一个图像加载...
//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;
&#34;故障&#34;您看到的是由多个setInterval
同时更改src
引起的。