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

时间:2012-07-30 11:44:00

标签: javascript jquery

我有一张如下表格。

<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(已完成)为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选择器访问元素。如果没有,我如何实施&#34; //如果td已经完成&#39;柱&#34;

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

假设您的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();

答案 1 :(得分:1)

$('#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();

答案 2 :(得分:0)

我可能会这样做:

$(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() selector“选择所有父元素为nth-child的元素”,因此$('#subtask_table td:nth-child(7)')选择第7列中的所有td元素。因此循环遍历这些单元格,如果文本内容是空字符串或“0”隐藏其父tr元素。

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