繁体   English   中英

jQuery如何更改每个表数据行的类?

[英]jQuery How to change class for each table data row?

我有数据表,我需要td:eq(4)更改类,以及baghround的框。

我有以下代码:

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

如果在这个时间点我的价值大于1,我会添加红色框。

但是Nox,出了点问题。

在没有看到您的html的情况下,我只能根据您的代码猜测其外观,但是请尝试以下操作:

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

首先,我将您的td:eq(4)分配给变量var mytd = $(this);
然后我用mytd替换$('.defects')

 $('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> 

您可以运行上面的演示并查看结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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