简体   繁体   中英

jQuery How to change class for each table data row?

I have table, with data, and i need for td:eq(4) change class, and box for baghround.

I have this code:

 $('tr').each(function () {
        var rowCol = $(this);
        rowCol.find('td:eq(4)').each(function () {
            var rowValue = parseFloat($(this).text());
            console.log(rowValue === 0)
            if (rowValue > 1) {
                $('.defects').addClass('def').removeClass('defects');
            } else {
                $('.def').addClass('defects').removeClass('def');
            }
        });
    });


.defects {
    background: #e74c3c;
    color: #fff;
    padding: 3px;
    border-radius: 6px;
}

And if at this td i have value more then 1, i add bg red box.

But nox, something went wrong.

Without seeing your html, I can only guess about how it looks based on your code, but try this:

$('tr').each(function() {
  var rowCol = $(this);
  rowCol.find('td:eq(4)').each(function() {
    var mytd = $(this);
    var rowValue = parseFloat($(this).text());
    console.log(rowValue === 0)
    if (rowValue > 1) {
      mytd.addClass('def').removeClass('defects');
    } else {
      mytd.addClass('defects').removeClass('def');
    }
  });
});

first of, I'm assigning your td:eq(4) to a variable var mytd = $(this); .
then I'm replacing $('.defects') with mytd

Code

 $('tr').each(function() { var rowCol = $(this); rowCol.find('td:eq(4)').each(function() { var mytd = $(this); var rowValue = parseFloat($(this).text()); console.log(rowValue === 0) if (rowValue > 1) { mytd.addClass('def').removeClass('defects'); } else { mytd.addClass('defects').removeClass('def'); } }); }); 
 .defects { background: #e74c3c; color: #fff; padding: 3px; border-radius: 6px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>0</td> <td>6</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> </tr> </table> 

You can run the demo above and see the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM