简体   繁体   English

如果列的值相同,如何更改表格行的背景颜色?

[英]How to change Background color of Table row if the value of column is same?

I want to set same and different background color of Table rows where the column value matches previous or next row of same for same column.我想为表行设置相同和不同的背景颜色,其中列值与同一列的上一行或下一行相同。

For example, Check the below table.例如,检查下表。

<table class="table table-striped">
<thead class="table-light fw-semibold">
    <tr class="align-middle">
        <th>Name</th>
        <th>Age</th>
        <th>Profession</th>
    </tr>
</thead>
<tbody>
    <tr class="align-middle">
        <td>
            John
        </td>
        <td>
            25
        </td>
        <td>
            Architect
        </td>
    </tr>
    <tr class="align-middle">
        <td>
            John
        </td>
        <td>
            35
        </td>
        <td>
            Teacher
        </td>
    </tr>
    <tr class="align-middle">
        <td>
            Jerry
        </td>
        <td>
            30
        </td>
        <td>
            Broker
        </td>
    </tr>
</tbody>

In the above table.在上表中。 The name column of the first row matches name of 2nd(next) row.第一行的名称列与第二(下)行的名称匹配。 So I want to set a different background color for both the matched rows.所以我想为两个匹配的行设置不同的背景颜色。

How can I do that using JS/jQuery?我怎样才能使用 JS/jQuery 做到这一点?

You may want to iterate the rows.您可能想要迭代行。 I wasn't sure which columns you wanted to compare with the previous row, so I compared all columns and if any match, I mark those rows with a background.我不确定您想将哪些列与前一行进行比较,所以我比较了所有列,如果匹配,我用背景标记这些行。

 var previous_values = new Array(100) var previous_row = null; document.querySelectorAll("tbody tr").forEach(function(row) { var i = 0; var found = false; row.querySelectorAll("td").forEach(function(td) { var value = td.innerText; if (value == previous_values[i]) { found = true; } previous_values[i] = value; i++; }) if (found) { row.classList.add("bg-primary"); if (previous_row) { previous_row.classList.add("bg-primary"); } } previous_row = row; })
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <table class="table table-striped"> <thead class="table-light fw-semibold"> <tr class="align-middle"> <th>Name</th> <th>Age</th> <th>Profession</th> </tr> </thead> <tbody> <tr class="align-middle"> <td> John </td> <td> 25 </td> <td> Architect </td> </tr> <tr class="align-middle"> <td> John </td> <td> 35 </td> <td> Teacher </td> </tr> <tr class="align-middle"> <td> Jerry </td> <td> 30 </td> <td> Broker </td> </tr> </tbody>

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

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