使用 JQuery 在 TR 中查找带有文本的第一个 TD
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13330778/
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
Find first TD with text in a TR with JQuery
提问by BarakChamo
I am using JQuery to iterate through all TRs in a table,
我正在使用 JQuery 遍历表中的所有 TR,
but not all rows have values in the first cell.
但并非所有行在第一个单元格中都有值。
<TR>
<TD>3</TD>
<TD>2</TD>
<TD>1</TD>
</TR>
<TD></TD>
<TD>3</TD>
<TD>2</TD>
<TR>
</TR>
<TR>
<TD></TD>
<TD></TD>
<TD>3</TD>
</TR>
How can i target the first TD in each row that is not empty and not just the first child?
我如何定位每行中的第一个非空的 TD 而不仅仅是第一个孩子?
Thanks!
谢谢!
回答by Dan Dascalescu
Here's a simpler, more elegant solution:
这是一个更简单、更优雅的解决方案:
$('tr').find('td:not(:empty):first').css('background', 'red');?
Fiddle: http://jsfiddle.net/dandv/JRcEf/
小提琴:http: //jsfiddle.net/dandv/JRcEf/
It just says in jQuery what you mean: "target the firsttd
in each tr
that is notempty".
它只是说,在jQuery的你的意思是:“目标的第一个td
在每个tr
是不空”。
回答by T.J. Crowder
This finds the first non-blank child td
within each tr
:
此发现的第一个非空白子td
中的每个tr
:
$("tr").each(function() {
var $firstNonEmptyCell;
$(this).children("td").each(function() {
var $td = $(this);
if ($td.text() === "") {
$firstNonEmptyCell = $td;
return false; // Breaks `each` loop
}
});
// ...use `$firstNonEmptyCell` here
});
Or if you want a jQuery wrapper for all non-blank ones, it's a trivial use case for filter
:
或者,如果您想要所有非空白的 jQuery 包装器,这是一个微不足道的用例filter
:
$("tr").each(function() {
var nonBlankCells = $(this).children("td").filter(function() {
return $(this).text() !== "";
});
// Use `nonBlankCells` here
});
回答by Kirill Ivlev
var tds = [];
$('#tableId tr').each(function()
{
$(this).find('td').each(function()
{
if ( $(this).html() != '' )
{
tds.push($(this));
return false;
}
});
});
and voila in the tds
variable you got your td tags
瞧,在tds
变量中你得到了你的 td 标签