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