2013-03-24 83 views
0

我創建了一個隨機的HTML頁面與內部jQuery,我試圖讓jQuery隱藏三個段落中的兩個,並做了5秒,但當我加載HTML文件,所有段落立即可見。誰能幫忙?jQuery,隱藏段落

<html> 
    <head> 
     <script src="jquery-1.9.1.js"></script> 
    </head> 
    <body> 
     <script> 
      var $ = jQuery; 
      $("p").each(function (idx) { 
       if(idx >= 1) { 
        $(this).hide(500); 
       } 
      }); 
     </script> 
     <p>This is the first paragraph</p> 
     <p>This is the second paragraph</p> 
     <p>This is the third paragraph</p> 
    </body> 
</html> 

回答

0

確保等待DOM準備的事件:

$(document).ready(function() { 
    // your code 
}); 
5

您有$()來包裝你的代碼,因爲元素尚未加載。

$(function(){ 
    $("p:not(:first-child)").hide(5000); 
}); 

TRY-A-DEMO

而且我相信500是一個錯字,因爲5000爲5秒。

由於@David Thomas建議,可以進一步簡化成:

$(function(){ 
    $("p:gt(0)").hide(5000); //:gt means "greater than..." 
}); 
+2

+1的選擇語法,而不是每個循環 – 2013-03-24 23:29:21

+1

雖然這一選擇的作品,爲什麼不進一步簡化:'$('P:GT( 0)')。hide();'或$('p')。slice(1).hide()'?雖然+1適當的選擇器*和*時間校正。當然,原生的CSS選擇器是:$('p + p')'和'$('p〜p')',它們允許選擇器傳遞給本地'document.querySelectorAll()'(在可用的瀏覽器中)。 – 2013-03-24 23:30:53

+0

@DavidThomas - 在我看來,這比':gt'更容易理解。 – 2013-03-24 23:33:06