2013-04-08 53 views
3

我有一個簡單的html表,它包含thead,tbody和tfoot。 我想選擇使用javascript或jquery所有th標籤只在thead內。 到目前爲止,我找到了一種方法來獲得所有的表或thead本身。獲取所有th標籤下的只有

我的表:

 <table id="MyTbl" class="display"> 
       <thead> 
        <tr> 
         <th> 
          ID 
         </th> 
         <th> 
          Name 
         </th> 
         <th> 
          Desc 
         </th> 
        </tr> 
       </thead> 
       <tbody id="MyTableBody"> 
       </tbody> 
       <tfoot> 
        <tr height="27px"> 
         <th class="TDHMain"> 
          FILTER ID 
         </th> 
         <th class="TDHMain"> 
          FILTER NAME 
         </th> 
         <th class="TDHMain"> 
          FILTER DESC 
         </th> 
        </tr> 
       </tfoot> 
      </table> 

我的javascript:

var table = document.getElementById('MyTbl'); 
var tableHeader = table.getElementsByTagName('thead'); 
var headers = tableHeader.getElementsByTagName('th'); //This one doesn't work. No such a method for the thead tag 

我也試過下面的代碼:

headers = $('#MyTbl').find('thead > th').get(); 

但作爲一個結果,我真的無法理解如何與它一起工作......這不是一個數組,對於我得到的標題對象沒有foreach函數,而且我真的無法完成找到一種方式來獲取數據。

無論如何只能得到表格中的第th元素嗎?

謝謝

回答

5

你可以把你所有的文字到一個數組:

var thArray = []; 

$('#MyTbl > thead > tr > th').each(function(){ 
    thArray.push($(this).text()) 
}) 

然後檢索它像這樣:

thArray[0]; // This will give you ID 

Demo

2

你可以這樣做;

$('#MyTbl thead').find('th'); 

OR

$('#MyTbl thead th').each(function() { 
    // Your code per th here 
}); 
1

嘗試

var tableHead = $('#MyTbl thead tr th'); 
0

哦!我錯過了「tr」。

我解決它通過以下方式:

headers = $('#MyTbl').find('thead > tr > th').get(); 
+1

可能花費更多時間來發布問題,而不是嘗試解決自己的問題。祝你好運編碼:) – 2013-04-08 07:59:44

+0

hummm>是父母的孩子選擇器...你使用的是> TH,這將始終返回空ASL只要沒有直接的孩子是TH。 – 2013-04-08 08:00:08

相關問題