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!
3 个解决方案
#1
19
Here's a simpler, more elegant solution:
这是一个更简单,更优雅的解决方案:
$('tr').find('td:not(:empty):first').css('background', 'red');
Fiddle: http://jsfiddle.net/dandv/JRcEf/
It just says in jQuery what you mean: "target the first td
in each tr
that is not empty".
它只是在jQuery中说你的意思:“定位每个非空的tr中的第一个td”。
#2
1
This finds the first non-blank child td
within each tr
:
这会在每个tr中找到第一个非空子td:
$("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包装器,它对于过滤器来说是一个简单的用例:
$("tr").each(function() {
var nonBlankCells = $(this).children("td").filter(function() {
return $(this).text() !== "";
});
// Use `nonBlankCells` here
});
#3
0
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标签
#1
19
Here's a simpler, more elegant solution:
这是一个更简单,更优雅的解决方案:
$('tr').find('td:not(:empty):first').css('background', 'red');
Fiddle: http://jsfiddle.net/dandv/JRcEf/
It just says in jQuery what you mean: "target the first td
in each tr
that is not empty".
它只是在jQuery中说你的意思:“定位每个非空的tr中的第一个td”。
#2
1
This finds the first non-blank child td
within each tr
:
这会在每个tr中找到第一个非空子td:
$("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包装器,它对于过滤器来说是一个简单的用例:
$("tr").each(function() {
var nonBlankCells = $(this).children("td").filter(function() {
return $(this).text() !== "";
});
// Use `nonBlankCells` here
});
#3
0
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标签