2012-03-09 29 views
4

通过显示文本找到列索引的好方法是什么?JQuery/Javascript - 如何通过标题文本找到表头索引

例如

<table> 
    <tr> 
    <td>ID</td> 
    <td>Name</td> 
    <td>Age</td> 
    </tr> 
    <tr> 
     ... 
    </tr> 
</table> 

我想有像

var nameIndex = getColIndex('Name'); // nameIndex = 1 

有没有做一个快速/好办法吗? (不必是jQuery的,但将是很好)

+0

我很好奇,想知道的大背景下你的问题。你是否期望'Name'在不同的列中,还是总是在'1'中? – 2012-03-09 19:37:08

+0

是的,列可能会移动......这就是为什么我想通过名称来找到它(这是不可变的) – 2012-03-09 19:40:04

+1

其他列是否可以包含Name的子字符串?或者如何处理空白。有没有可能出现领先或尾随空白,如换行符? – 2012-03-09 19:41:46

回答

16

似乎都工作,铬17/Ubuntu的11.04如下:

$('tr td').filter(
    function(){ 
     return $(this).text() == 'Name'; 
    }).index(); 

JS Fiddle demo

或者:

$('td:contains("Name")').index(); 

JS Fiddle demo


响应编辑到OP的问题,在注释中,如下所示:

但我怎么把它限制在第一排?

要限制它的第一行,只需使用:first选择:

$('tr:first td') 

,并提供:

$('tr:first td').filter(
    function(){ 
     return $(this).text() == 'Name'; 
    }).index(); 

JS Fiddle demo

参考文献:

+0

谢谢,但我怎么限制它到第一行?这是我有点困惑的地方 – 2012-03-09 19:36:47

+0

我将此添加到您的解决方案以限制到第一行... var index = $('tr:eq(0)td:contains(“Name”)')。index (); http://jsfiddle.net/9uPWe/ – 2012-03-09 19:41:51

+0

选择器将是$('tr:eq(0)td') – 2012-03-09 19:42:38

2
//select the first TR element, then select its children (the TDs), 
//then filter them down to only the one that contains a certain string 
var theIndex = $('tr').first().children().filter(function() { 
    return ($(this).text() == 'ID'); 
}).index(); 

传递.filter()当一个功能,如果一个指数收益率true,那么它将被保存在选择,如果你返回false那么指数将会从选择中删除:http://api.jquery.com/filter

这会将搜索限制在第一行,并给出指定搜索文本的列索引(此代码使用ID)。

注意.index(),像上面使用时,将返回当前选择的基于其同级元素的索引:http://api.jquery.com/index

1

http://jsfiddle.net/justiceerolin/FdhcV/

$(function(){ 
    $('#search').click(function(){ 
     $('td').each(function(index){ 
      if ($(this).text() == $('#lookup').val()){ 
       console.log(index) 
      } 
     });  
    }); 
});​ 
+0

漂亮的搜索框... – 2012-03-09 19:47:58