JQuery:如何从表中选择行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3585272/
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: How to select rows from a table
提问by nabeelfarid
I have a scenario where I would like to select rows from a table depending upon the values in td
我有一个场景,我想根据 td 中的值从表中选择行
e.g. I have a table like this
例如我有一张这样的桌子
<tr>
<td>John</td>
<td>Smith</td>
<td>Male</td>
</tr>
<tr>
<td>Andy</td>
<td>Gates</td>
<td>Male</td>
</tr>
<tr>
<td>Alice</td>
<td>Nixon</td>
<td>Female</td>
</tr>
now I would like to select all the rows if the value of first td is x ANDvalue of second td is y
现在我想选择所有行,如果第一个 td 的值是 x ,第二个 td 的值是 y
At the momemnt I am doing something like this
目前我正在做这样的事情
$("tr").each(function (index) {
if ($(this).find('td:eq(0)').text().trim() == x &&
$(this).find('td:eq(1)').text().trim() == y)
...do somethin....
});
looping through each row and check. This is verbose. Is there a better way to achieve this in a single line. I can't seem to figure out AND operator logic with selectors?
遍历每一行并检查。这是冗长的。有没有更好的方法可以在一行中实现这一点。我似乎无法弄清楚选择器的 AND 运算符逻辑?
Awaiting,
等待,
回答by karim79
$("tr").each(function (index) {
if ($.trim($(this).find('td:eq(0)').text()) == x &&
$.trim($(this).find('td:eq(1)').text()) == y) {
$(this).closest('table').css('border', '1px solid red');? // this should do it
}
});
Alternatively, using .filter
:
或者,使用.filter
:
$("tr").filter(function() {
return $.trim($(this).find('td:eq(0)').text()) == 'John' &&
$.trim($(this).find('td:eq(1)').text()) == 'Smith';
}).closest('table').find('tr').css('border', '1px solid red');?
回答by user113716
Here's a selector that should work:
这是一个应该可以工作的选择器:
Try it out:http://jsfiddle.net/N6TdM/
试试看:http : //jsfiddle.net/N6TdM/
var x = "Andy";
var y = "Gates";
var res = $("td:first-child:contains(" + x + ") + td:contains(" + y + ")");
Note that this couldfail if you have something like the following:
请注意,如果您有以下内容,这可能会失败:
FIRST: Roberto Rob
SECOND: Robertson Roberts
Searching for "Rob Roberts" would give two matches.
搜索“Rob Roberts”会得到两个匹配项。
回答by bobince
You can use the native DOM cells
propertyon the HTMLTableRowElement to access the cells directly, rather than sending jQuery on a roundabout trip with listing all descendant cells and picking out one with the non-standard :eq
selector.
您可以使用HTMLTableRowElement 上的本机 DOMcells
属性直接访问单元格,而不是在迂回行程中发送 jQuery,列出所有后代单元格并使用非标准:eq
选择器挑选一个。
$('tr').each(function (index) {
if (
$(this.cells[0]).text().trim()===x &&
$(this.cells[1]).text().trim()===y
) {
...
}
});
though it probably won't make a serious performance difference. Another approach would be simply to maintain an array-of-arrays containing the pre-trimmed data to save even looking at the DOM.
虽然它可能不会产生严重的性能差异。另一种方法是简单地维护一个包含预修剪数据的数组数组,以节省查看 DOM 的时间。