如何根据某列中的值隐藏表行

How to hide a table row depending on a value in one of its column

本文关键字:隐藏 何根      更新时间:2024-04-22

我有一个如下表。

<table id="subtask_table" style="width: 80%">
    <tr>
        <th>ID</th>
        <th>Titel</th>
        <th>Beschreibung</th>
        <th>Gemeldet von</th>
        <th>Erstellt am</th>
        <th>Geändert am</th>
        <th>Erledigt</th>

    </tr>
    <tr>
        <td>11</td>
        <td><a href="/taskExplorer/subtasks/edit/11">Termine verschieben</a></td>
        <td></td>
        <td></td>
        <td>2012-07-26 14:34:36</td>
        <td>2012-07-30 08:37:40</td>
        <td>1</td>
        <td><a href="/taskExplorer/subtasks/delete/11">löschen</a></td>
      </tr>
</table>

如果列erledigt(completed)为0或为空,我想隐藏该表的一行。

这就是我目前所得到的:

$(document).ready(function() {
    $('#cbHideCompleted').click(function() {
        if($(this).prop('checked')) {
            $('#subtask_table td').each(function() {
                //if td is 'completed' column
                    //if value is 0 or null
                        //hide
            });
        } else {
            $('#subtask_table td').each(function() {
                $(this).show();
            });
        }
    });
});

有没有一种方法可以使用jquery选择器直接访问元素。如果没有,我如何实现"//如果td是‘completed’列"?

谢谢你的帮助。

假设erledigt列总是倒数第二列,那么它应该是非常直接的。

遍历行而不是单元格,找到每行中倒数第二个单元格,并根据需要显示/隐藏该行。

$('#subtask_table tr').each(function() {
    var $erledigtCell = $(this).find("td").last().prev();
    var $row = $erledigtCell.parent();
    if($erledigtCell.text() == '1'){
        $row.hide();
    } else {
        $row.show();
    }
});

如果您对网格的生成方式有任何影响,那么如果您可以向tr添加自定义属性(例如data-erledigt=...)会更好。然后你没有遍历要做,并且在哪个列中显示erledigt也无关紧要。

Html如下:

<tr data-erledigt=0>....
.....
<tr data-erledigt=1>

您可以编写一个简单的jQuery:

$("tr[data-erledigt='0']").hide();
$('#subtask_table tr td:eq(6)').each(function() { // eq(6) selects the 7-th td, which is the "completed" column
    if(this.innerHTML === '0' || this.innerHTML === '')
    {
        $(this).parent().hide(); // td.parent returns the tr
    }
});

此外,这是多余的(尽管我不确定这能实现什么,但也许你想显示行(tr而不是td)):

$('#subtask_table td').each(function() {
    $(this).show();
});

简单使用:

$('#subtask_table td').show();

我可能会这样做:

$(document).ready(function() {
    $('#cbHideCompleted').click(function() {
        if($(this).prop('checked')) {    
            $('#subtask_table td:nth-child(7)').each(function() {
                //if td is 'completed' column
                var val = $(this).text();
                if (val === "" || val === "0")
                    $(this).parent().hide();    
            });
        } else {
            $('#subtask_table tr').show();
        }
    });
});

:nth-child()选择器"选择其父元素的第n个子元素",因此$('#subtask_table td:nth-child(7)')选择第7列中的所有td元素。因此,在这些单元格中循环,如果文本内容是空字符串或"0",则隐藏其父tr元素。

在else分支中,您不需要.each()循环:您可以直接对包含多个元素的jQuery对象调用.show(),所有元素都将显示出来。