2013-04-08 54 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

相关问题