2011-02-10 19 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)