JQuery / Javascript - 如何通过标题文本查找表标题的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9639887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery / Javascript - How to find the index of a table header by the header text
提问by Eran Medan
What is a good way to find the index of column by it's display text?
通过显示文本查找列索引的好方法是什么?
e.g.
例如
<table>
<tr>
<td>ID</td>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
...
</tr>
</table>
I would like to have something like
我想要类似的东西
var nameIndex = getColIndex('Name'); // nameIndex = 1
Is there a quick / good way to do it? (Doesn't have to be jQuery, but would be nice)
有没有快速/好的方法来做到这一点?(不必是 jQuery,但会很好)
回答by David says reinstate Monica
The following both seem to work, in Chromium 17/Ubuntu 11.04:
在 Chromium 17/Ubuntu 11.04 中,以下两者似乎都有效:
$('tr td').filter(
function(){
return $(this).text() == 'Name';
}).index();
Or:
或者:
$('td:contains("Name")').index();
Editedin response to OP's question, in comments, below:
针对 OP 的问题进行了编辑,在评论中,如下:
but how do I limit it to the first row?
但是如何将其限制在第一行?
To limit it to the first row, simply use the :first
selector:
要将其限制在第一行,只需使用:first
选择器:
$('tr:first td')
Giving:
给予:
$('tr:first td').filter(
function(){
return $(this).text() == 'Name';
}).index();
References:
参考:
回答by Jasper
//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();
When passing .filter()
a function, if you return true
for an index, then it will be kept in the selection, and if you return false
then that index will be removed from the selection: http://api.jquery.com/filter
传递.filter()
函数时,如果返回true
索引,则它将保留在选择中,如果返回,false
则该索引将从选择中删除:http: //api.jquery.com/filter
This will limit the search to the first row and give the index of the column with the specified search text (this code used ID
).
这会将搜索限制在第一行并给出具有指定搜索文本的列的索引(此代码使用ID
)。
Note that .index()
, when used like above, will return the index of the current selection based on its sibling elements: http://api.jquery.com/index
请注意.index()
,当像上面一样使用时,将根据其兄弟元素返回当前选择的索引:http: //api.jquery.com/index
回答by Justice Erolin
http://jsfiddle.net/justiceerolin/FdhcV/
http://jsfiddle.net/justiceerolin/FdhcV/
$(function(){
$('#search').click(function(){
$('td').each(function(index){
if ($(this).text() == $('#lookup').val()){
console.log(index)
}
});
});
});?