2011-02-10 61 views
2

我剛剛發現兒童大小不一致。jquery .children()返回錯誤的大小

下面附帶完整的代碼和警報,以便於參考。

我得到的數據是錯誤的嗎?

<body> 
<table width="100" border="0" cellspacing="0" cellpadding="0"> 
     <tr> 
     <td height="30" valign="top"><strong>Header Title</strong></td> 
     </tr> 

     <tr> 
      <td height="32" valign="top">Date : <strong>01/01/2010 </strong> <br><div><b></b></div><span></span></td> 
     </tr> 
</table> 
</body> 

$("td").each(function() { 
    alert($(this).children().size()); 
}); 

//first td showing 1 direct children- <strong> 
//second td showing 4 direct children- <strong> <br> <div> <span> 

----- 

$("tr").each(function() { 
    alert($(this).children().size()); 
}); 

//first tr showing 1 direct children - <td> 
//second tr showing 1 direct children - <td> 

----- 

$("table").each(function() { 
    alert($(this).children().size()); 
}); 

// ERROR 
// this table showing 1 direct children only.... something WRONG. 
// I thought there are 2 <tr> inside this table? 
+0

順便說一下,你有什麼算?表中的行?只要做一個$(「tr」).length然後。或者如果你有很多表格,添加一個id到你的表格並以$(「#tableid tr」) – corroded 2011-02-10 09:03:27

回答

6

的原因是,你沒有你的表內的<tbody>。瀏覽器自動爲你添加這個,因此它成爲<table>的唯一孩子。

你可能有興趣在運行這段代碼:

alert($('table').children()[0].tagName); 
+0

的形式訪問它,這有點棘手。如果某些瀏覽器永遠不會幫助你添加tbody,該怎麼辦?那麼它將會跨瀏覽器問題。 – 2011-02-10 07:37:15

+0

@我需要幫助,最好的選擇是自己總是在HTML中包含``。 – 2011-02-10 07:38:55

0

你問TD的孩子的大小,並在你的結構,你的TD只有一個孩子:強烈的標籤。

在你的第二個問題中,你問你的孩子們。每個tr標籤只有1個td,因此它只顯示1個。

試試這個:

alert($("tbody").children().length)