2012-07-09 104 views
0

這是正確的jQuery語法,用於檢查div是否隱藏& &有一類「view」?如果確實如此,那麼在.3秒之後,揭示下一個隱藏的div與「視圖」級別?if jquery中的語句

注意它目前沒有工作,但它會淡入所有隱藏的divs,而不管任何類。

<script type="text/javascript"> 
      $(function() { 
       // Start showing the divs 
       showDiv(); 
      }); 

      function showDiv() { 
       // If there are hidden divs left 
       if($('div:hidden').length.hasClass('view')) { 
        // Fade the first of them in 
        $('div:hidden:first').fadeIn(); 
        // And wait one second before fading in the next one 
        setTimeout(showDiv, 300); 
       } 
      } 
    </script> 
+3

什麼是.length.hasClass()? – 2012-07-09 21:09:24

+0

你的問題有更多的與jQuery選擇器相比,如果語句在* Javascript * – Radu 2012-07-09 21:11:16

+0

隱藏的div不是空的,有一類'視圖'?我能結合那樣的條件嗎?還是應該用&&來代替? – kikix2125 2012-07-09 21:11:44

回答

4

可能是一個更好的解決方案是

if($('div.view:hidden').length) { 
    // Fade the first of them in 
    $('div.view:hidden:first').fadeIn(); 
    // And wait one second before fading in the next one 
    setTimeout(showDiv, 300); 
} 
+1

不應該是'if($('div.view:hidden')。length)'? – 2012-07-09 21:10:54

+0

@PhilippeLeybaert,我的複製和粘貼失敗了我。 – 2012-07-09 21:11:27

+2

更好的是,如果它不保存重定向:var divs = $('div.view:hidden')',然後使用['divs.first()'](http://api.jquery.com/first /) – bdukes 2012-07-09 21:16:20

2
// get all hidden divs with a class of view 
var $hiddenViewDivs = $('div.view:hidden'); 
// if there are any... 
if ($hiddenViewDivs.length) { 
    // get the first one and invoke fadeIn() on it 
    $hiddenViewDivs.first().fadeIn(); 
    // And wait one second before fading in the next one 
    setTimeout(showDiv, 300); 
} 

我會解釋你的代碼在做什麼(看看我的新的意見與周圍星):

// **Get the length (count) of all hidden divs and invoke hasClass('view') on that number (will throw an error)** 
if($('div:hidden').length.hasClass('view')) { 
    // **Get the first hidden div and invoke fadeIn() on it, regardless of if it has a class of view or not** 
    $('div:hidden:first').fadeIn(); 
    // And wait one second before fading in the next one 
    setTimeout(showDiv, 300); 
} 

編輯(備用解決方案):

該解決方案的優點是您不必在DOM中繼續查找$('div.view:hidden')。在這裏,你得到一次,安撫表演神。

function showDiv() { 
    var $hiddenViewDivs = $('div.view:hidden'); 
    var i = 1; 
    $hiddenViewDivs.each(function(){ 
     (function($target){ 
      setTimeout(function(){$target.fadeIn();}, 300*i); 
     })($(this)); 
     i++; 
    }); 
}​ 

例子: http://jsfiddle.net/lbstr/LdzYm/

+0

非常酷!謝謝! – kikix2125 2012-07-09 23:09:17

0

如何只$('div.view:hidden').length

0
$('div.view:hidden:first').fadeIn(function() { 
    setTimeout(showDiv, 300); 
}); 

你不需要if。 jQuery將爲你照顧。