1

我有 5 个项目的集合,我希望每个项目显示 5 秒。这是以下 HTML 代码:

<div class="show">
 <rec>First item</rec>
 <rec>Second item</rec>
 <rec>Third item</rec>
 <rec>Fourth item</rec>
 <p class="show-line"></p>
</div>   

这里是 Jquery

 $('.show > rec').hide();

 $('rec').each(function(index) { 
  var x = $(this).text();
    setTimeout(function() {
      $('p.show-line').html(x).fadeIn('slow');  
    }, 5000);

 });

现在的问题是在 show-line 元素中只输出了最后一项。但是当我提醒 x 元素时,它会输出正确的值。那么我怎样才能将每个元素显示 5 秒,然后隐藏并显示下一个元素等等......

这是一个工作示例http://jsfiddle.net/3NnR2/11/

肿瘤坏死因子

4

4 回答 4

1

另一种选择是使用setInterval方法,然后根据索引选择要显示的元素:

$('.show > rec').hide();

var index = 0;
var total = $('rec').size() - 1;

setInterval(function(){

    var rec = $('rec:eq(' + index + ')');
    $('p.show-line').html(rec.text()).fadeIn("slow");

    if(index == total){
        index = 0;
    } else {
        index++;
    }

}, 5000);

工作示例:http: //jsfiddle.net/3NnR2/15/

于 2012-12-22T18:24:56.363 回答
0
  1. 您需要为每个设置不同的 setTimeout 间隔。
  2. 您还需要.hide()之前的元素.fadeIn()

尝试以下操作:

$('.show > rec').hide();

$('rec').each(function(index) { 
    var x = $(this).text();
    setTimeout(function() {
       $('p.show-line').html(x).hide().fadeIn('slow');  
     }, index * 5000);

});
于 2012-12-22T18:17:01.007 回答
0

你在这里做错了几件事。

  1. 无文件准备功能
  2. 你在fadeIn错误的元素上调用(.show-line而不是rec

以下是如何实际做到这一点:

$(document).ready(function(){
    $('.show > rec').hide();
    showNext($("rec:first-child"));

});

function showNext($ele){
    $ele.fadeIn('slow'); 
    if ($ele.next("rec").length > 0)
         setTimeout(function() {
           showNext($ele.next("rec"))  
         }, 5000);
}
于 2012-12-22T18:26:10.780 回答
0

把我的答案也扔进去。看起来这是一种流行的方法,看到使用的各种技术很有趣。

var i = 0;
var items = [];

$('.show > rec').hide();

$('rec').each(function(index) {
    var x = $(this).text();
    items[items.length] = x;
});

function rotate() {

    setTimeout(function() {
        if (i > items.length) {
            i = 0;
        }
        $('p.show-line').html(items[i]).hide().fadeIn('slow');
        i++;
        rotate();
    }, 5000);
}

rotate();​

基本思想只是将项目填充到一个数组中,然后使用递归永远循环它们。工作示例:http: //jsfiddle.net/3NnR2/17/

于 2012-12-22T18:35:36.327 回答