【问题标题】:Jquery loop through arrayJquery循环遍历数组
【发布时间】:2013-05-01 01:10:18
【问题描述】:

这个问题已经被问过很多次了,但是作为一个初学者,我很难将其他人的脚本应用到我自己分配的类和变量中。

我想知道的是:

我在 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);

提前感谢您的阅读!

【问题讨论】:

标签: jquery arrays loops


【解决方案1】:

基本上,您将不得不使用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

【讨论】:

  • 我认为应该是 index >= hobbies.length 或 index == hobbies.length
  • 这正是我想要的!非常感谢!
【解决方案2】:

试试这样的 -

    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

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 2019-03-25
    • 2017-01-29
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多