不断循环javascript数组并将结果显示给div? [英] Constantly loop a javascript array and display results to div?
本文介绍了不断循环javascript数组并将结果显示给div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的网站上有一堆推荐信,目前正在页面上,我试图让div以5秒的间隔显示每个1,如果数组达到最后一个值,它应该重新开始数组再次。
I have a bunch of testimonials for my site which are currently on a page and am trying to get a div to display each 1 at an interval of 5 seconds, if the array reaches the last value it should start back to beginning of the array again.
这是我到目前为止所拥有的......
Here is what I have so far...
var testimonial = new Array();
testimonial[1] = "Rugby";
testimonial[2] = "Baseball";
testimonial[3] = "Cricket";
var length = testimonial.length
var i = 1;
setInterval(function() {
while (i <= length) {
$('#testimonials p').html(testimonial[i]);
++i;
if (i == length) {
i == 1;
}
}
}, 5000);
任何帮助都会很棒,谢谢。
Any help would be great, thanks.
推荐答案
尝试
var testimonial = ['Rugby', 'Baseball', 'Cricket'];
var numTestimonials = testimonial.length;
var index = 0;
setInterval(function() {
$('#testimonials p').text(testimonial[index]);
index = (index + 1) % numTestimonials;
}, 5000);
JavaScript数组是0索引的,并且具有方便的数组文字语法。使用模数运算符(%
)是一种惯用的方法,一旦计数器达到某个值就将其包装回0。
JavaScript arrays are 0-indexed and have handy array literal syntax. Using the modulus operator (%
) is an idiomatic way of wrapping a counter back to 0 once it reaches a certain value.
这篇关于不断循环javascript数组并将结果显示给div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文