2012-02-21 54 views
1

如何在搜索特定元素時獲得直接的孩子?例如,我想獲得表t1tr元素。尋找直接的孩子,不再進一步使用jQuery

<table id="t1" bgcolor="yellow"> 
     <tbody> 
      <tr> 
       <td>This is Cell 1</td> 
       <td>This is Cell 2</td> 
      </tr> 
      <tr> 
       <td>This is Cell 3</td> 
       <td> 
        <table id="t2" bgcolor="red"> 
         <tbody> 
          <tr> 
           <td>This is Cell 1</td> 
           <td>This is Cell 2</td> 
          </tr> 
          <tr> 
           <td>This is Cell 3</td> 
           <td>This is Cell 4</td> 
          </tr> 
         </tbody> 
        </table> 
       </td> 
      </tr> 
     </tbody> 
    </table> 

我嘗試這樣做:

'Count = ' + $('#t1 tbody').children('tr').length; 

不過,我得到的4計數,我不明白爲什麼?

Here是一個完整的例子:

回答

5

用途:

'Count = ' + $('#t1 > tbody').children('tr').length; 
// or: $("#t1 > tbody > tr").length 
// or: $("#t1")[0].rows.length; // In this case, equal to previous code. 
           // Warning: This also includes the rows from 
           // the <thead> and <tfoot> sections. 

您當前的代碼顯示4,因爲你已經得到了在表#t1 2個<tbody>元素:

<table id="t1" bgcolor="yellow">   <-- #t1 
    <tbody>        <--- tbody 
     <tr> ... </tr>      <----- Child 1 
     <tr> ...       <----- Child 2 
        <tbody>    <--- tbody (unexpected?) 
         <tr> ... </tr>  <----- Child 3 
         <tr> ... </tr>  <----- Child 4 
        </tbody> 
       </table> 
      </td> 
     </tr> 
    </tbody> 
</table> 
+0

啊!我正在努力注意那些遺忘了身體的tr。浪費了一個小時。感謝Rob! – Abs 2012-02-21 21:28:19