Jquery循环遍历数组

时间:2013-04-30 16:25:00

标签: jquery arrays loops

这个问题已被多次提出,但作为一个初学者,我很难将其他人的脚本应用到我自己指定的类和变种中。

我想知道的是:

我在html中有一个简单的区域,如下所示:

<h1>I like: <span class ="hobbies">array items go here</span></h1>

我已经制作了一个阵列:

var hobbies=new Array("graphic design.","photography.", "videography.", "marketing.", "craft beers.")

我希望每个项目自己显示3秒钟左右然后逐渐消失并被数组中的下一个项目替换。我还想在完成所有选项后循环。我怎么能这样做?

我也有:

$('.hobbies').html(hobbies);

提前感谢您阅读!

2 个答案:

答案 0 :(得分:3)

基本上,您将不得不使用setInterval在特定时间延迟时重复该功能。

在hobbies数组中保存当前位置的索引,并在每次迭代时增加索引。确保在索引达到与数组长度相同的值时重置索引。

// Always a good idea to cache selectors you're gonna be using alot.
var hobbyContainer = $('.hobby');
hobbyContainer.text(hobbies[0]);
var index = 1;
setInterval(function(){
  hobbyContainer.fadeOut('fast',function(){
    hobbyContainer.text(hobbies[index]);
    index++;
    if (index >= hobbies.length){
      index = 0;
    }
  }).fadeIn('fast');
},3000);  

您可能必须使用间隔的持续时间才能为淡入淡出的动画留出时间。或者你可以像我在我的例子中那样更快地制作淡入淡出动画。

Here is a simple demo on jsFiddle

答案 1 :(得分:0)

尝试这样的事情 -

    var hobbies = //"yourarray";
    var count = 0;
    setInterval(function() {
        scrollText(hobbies[count]);
        count++;
        if (count == hobbies.length ) {
            count = 0;
        }
    }, 3000);


function scrollText(text) {     
    $(".hobbies").animate({opacity:0},function(){
        $(this).html(text).animate({opacity:1});  
    });
}

<强> Working Demo