检查表行中的单元格是否等于0,如果是则隐藏行

时间:2015-02-12 16:53:45

标签: javascript jquery html

基本上我要做的是迭代表行并检查除第一列之外的所有行是否等于零。如果是,则隐藏该行。

<table id="table">
    <thead>
        <tr>
            <th>Player</th>
            <th>Move 1</th>
            <th>Move 2</th>
            <th>Move 3</th>
            <th>Move 4</th>
            <th>Move 5</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John</td>
            <td>0</td>
            <td>0</td>
            <td>0</td>
            <td>0</td>
            <td>0</td>
        </tr>
        <tr>
            <td>James</td>
            <td>0</td>
            <td>5</td>
            <td>3</td>
            <td>4</td>
            <td>0</td>
        </tr>
    </tbody>
</table>

因此,在上表中,第一行将被隐藏,第二行将被显示。

非常感谢任何帮助!


更新:示例:http://jsfiddle.net/3rnbk6s5/

$('#table tr td').each(function() {
    if ($(this).text() === '0'){
        $(this).css('color', 'red');
    }
});

1 个答案:

答案 0 :(得分:2)

您需要查找行,评估每行中的单元格,并在行符合您的条件时应用隐藏类: JSFiddle Demo

var tbl = document.getElementById('table');         //find the table
var rows = tbl.querySelectorAll('tbody tr');        //find all rows in the table body

for(i = 0; i < rows.length; i++) {                  //iterate through the rows

    var cells = rows[i].querySelectorAll('td');     //find all of the cells in the row

    var flag = true;                                //set flag prior to cell evaluation

    for(j = 2; j < cells.length; j++) {             //iterate through the cells (starting with the cell at position 2)
        if (cells[j].innerHTML != '0') {            //check if the cell contains '0' (set flag to false if cell is not '0')
            flag = false;                           
        }
    }

    if(flag) { 
        rows[i].classList.add('hide');              //hide the row if the falg remained true (i.e. none of the cells contained a value other than '0'
    }
}
相关问题