2012-03-09 60 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