使用JQuery在TR中查找带有文本的第一个TD

时间:2012-11-11 11:43:09

标签: jquery html html-table

我正在使用JQuery迭代表中的所有TR,

但并非所有行都在第一个单元格中有值。

<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>

我如何定位非空的每一行中的第一个TD而不仅仅是第一个孩子?

谢谢!

3 个答案:

答案 0 :(得分:19)

这是一个更简单,更优雅的解决方案:

$('tr').find('td:not(:empty):first').css('background', 'red');​

小提琴:http://jsfiddle.net/dandv/JRcEf/

它只是在jQuery中说出你的意思:“在为空”的每个td中定位第一个 tr

答案 1 :(得分:1)

这会在每个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
});

或者如果你想要一个非空白的jQuery包装器,那对filter来说是一个简单的用例:

$("tr").each(function() {
    var nonBlankCells = $(this).children("td").filter(function() {
        return $(this).text() !== "";
    });

    // Use `nonBlankCells` here
});

答案 2 :(得分:0)

var tds = [];

$('#tableId tr').each(function()
{
  $(this).find('td').each(function()
  {
    if ( $(this).html() != '' )
    {
      tds.push($(this));
      return false;
    }
  });
});

并在tds变量中添加了你的td标签