Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

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

I have a table like the following.

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

What I want to do is hide a row of this table, if the column erledigt (completed) is 0 or empty.

That's what I got this far:

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

Is there a way to access the elements directly with a jquery selector. If not, how do I implement "//if td is 'completed' column"?

Thanks for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming your erledigt column is always the second last column then it should be very straight forward.

Iterate through the rows and not the cells and find the second last cell in each row and show/hide the row as required.

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

If you have any influence on how the grid is generated it would be much better if you can add a custom attribute to the tr, for example data-erledigt=.... Than you have no traversing to do and it doesn't matter which column erledigt is displayed in.

With Html like this:

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

You could write a jQuery as simple as:

$("tr[data-erledigt='0']").hide();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...