2012-12-22 83 views
1

我有一個喜歡5個項目的集合,我想爲每個項目顯示5秒鐘。 這裏是下面的HTML代碼:在jquery.each中每5秒鐘顯示一次對象值

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

}); 

現在的問題是,只有最後一個項目在展會線元件輸出。 但是,當我提醒x元素其輸出正確的值。所以,我怎麼可以顯示像每5秒元素,則隱藏和顯示下一個元素等等......

這裏是一個工作示例http://jsfiddle.net/3NnR2/11/

TNX

+0

**每隔5秒**是'setInterval',**下5秒**是'setTimeout' – balexandre

+0

btw,請參閱我的[回覆](http://stackoverflow.com/a/ 13967834/28004)關於其他問題和我的[現場示例](http://jsbin.com/osepim/1/edit)。也許你正試圖得到那樣的東西......不是嗎? – balexandre

回答

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/

+0

對於淡入淡出效果,需要使用hide()函數。因此,該行將爲 $('p.show-line')。html(rec.text())。hide()。fadeIn('slow'); – DownDown

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

}); 
+0

真的很不錯,有效!我怎樣才能讓這個循環繼續,所以在第一次啓動的最後一個元素之後呢? – DownDown

+0

使用SetInterval將保持循環遍歷項目,請參閱我的演示答案。 –

0

你在這裏做了一些錯誤的事情。

  1. 沒有文件準備功能
  2. 你的錯誤的元素(的.show-line代替rec)上調用fadeIn

Here is如何能真正做到這一點:

$(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); 
} 
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/