开发者

Dynamically change CSS class of a row in a table

I have a simple table:

<table> <t开发者_如何学编程r class="none"><td>value</td><td>value</td></tr></table>

I then need to check all the values of the cells in every row. If all of the values are not the same for a given row, then I need to change the class of the row from "none" to "active". Is there a way to do this using jQuery?


Something like the below would work. Also, I would recommend using <thead> and <tbody> in your <table> for proper markup. Update: corrected function below to check values of other rows; as soon as a different value is encountered, the <tr> is updated with a class accordingly.

Fiddle Demo: http://jsfiddle.net/kaCAF/4/

<script type="text/javascript">
$(document).ready(function() {
    $('#myTable tbody tr').each(function() {

        //compare each cell to adjacent cells
        $(this).find('td').each(function() {
            var $val = $(this).text();

            //checks for different values.  as soon as a difference
            //is encountered we move to next row
            $(this).parent().find('td').each(function() {
                if ($(this).text() != $val) {
                    $(this).parent().addClass('different');
                    return false;
                }
            });
        });
    });

});
</script>

<table id="myTable" border="1">
    <thead>
        <tr><th>Col1</th><th>Col2</th><th>Col3</th></tr>
    </thead>
    <tbody>
        <tr><td>Val 1</td><td>Val 1</td><td>Val 2</td></tr>
        <tr><td>Val 1</td><td>Val 2</td><td>Val 2</td></tr>
        <tr><td>Val 3</td><td>Val 3</td><td>Val 3</td></tr>
        <tr><td>Val 123</td><td>Val 123</td><td>Val 123</td></tr>
    </tbody>
</table>


If the value of the cell changes dynamically and you just want all the cells to match, try:

$(document).ready(function() {
    var baseval = "";
    $("table tr.active td").each(function() {
        if (baseval == "") {
            baseval = $(this).text();
        }
        else {
            if ($(this).text() != baseval) {
                $(this).parents("tr").removeClass("active");
                $(this).parents("tr").addClass("none");
            }
        }

    });

});

Demonstrated Here: http://jsfiddle.net/thomas4g/VVTjb/3/


You can get first td and compare to other:
See http://jsfiddle.net/bouillard/maCBh/


$(document).ready(function () {
    $('table tr').each(function(){
       var cells = $(this).find('td');
       if(!compareCells(cells)){
          $(this).addClass('active');
       }
    });    
});

 function compareCells(cells){
    var i = cells.length;
    for (i=0;i<cells.length-1;i++)
    {
        if($(cells[i]).html() != $(cells[i+1]).html()){
            return false;
        }
    }
    return true;

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜