You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为DataTable偶数Office行组实现排序后动态背景色?

Got it, let's fix this background color issue with your DataTables setup. The core problem with your current code is that it only swaps classes when you click a header, but doesn't recalculate which Office groups should be grey after the table sorts. Instead of relying on header click events, we need to hook into DataTables' built-in draw.dt event—this fires every time the table redraws (including after sorting), so we can reapply the background colors correctly every time.

Here's the Updated Solution

First, we'll replace your header click handler with the draw.dt event listener, then add logic to group rows by Office and apply the grey background to even-positioned groups (1-based, which translates to odd indices in 0-based arrays):

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">
<style>
.bg-dark-grey{ background-color: rgba(0,0,0,.05) !important; }
.bg-white{ background-color: #ffffff !important; }
</style>
<table id="example" class="xdisplay" style="width:100%">
  <thead>
    <tr>
      <th class="no-sort">Name</th>
      <th class="no-sort">Position</th>
      <th class="office">Office</th>
      <th>Age</th>
      <th class="no-sort">Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr class="bg-white">
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
      <td>61</td>
      <td>2011/04/25</td>
      <td>$320,800</td>
    </tr>
    <tr class="bg-white">
      <td>Quinn Flynn</td>
      <td>Support Lead</td>
      <td>Edinburgh</td>
      <td>22</td>
      <td>2013/03/03</td>
      <td>$342,000</td>
    </tr>
    <tr class="bg-white">
      <td>Cedric Kelly</td>
      <td>Senior Javascript Developer</td>
      <td>Edinburgh</td>
      <td>22</td>
      <td>2012/03/29</td>
      <td>$433,060</td>
    </tr>
    <tr class="bg-white">
      <td>Sonya Frost</td>
      <td>Software Engineer</td>
      <td>Edinburgh</td>
      <td>23</td>
      <td>2008/12/13</td>
      <td>$103,600</td>
    </tr>
    <tr class="bg-dark-grey">
      <td>Ashton Cox</td>
      <td>Junior Technical Author</td>
      <td>San Francisco</td>
      <td>66</td>
      <td>2009/01/12</td>
      <td>$86,000</td>
    </tr>
    <tr class="bg-dark-grey">
      <td>Herrod Chandler</td>
      <td>Sales Assistant</td>
      <td>San Francisco</td>
      <td>59</td>
      <td>2012/08/06</td>
      <td>$137,500</td>
    </tr>
    <tr class="bg-white">
      <td>Garrett Winters</td>
      <td>Accountant</td>
      <td>Tokyo</td>
      <td>63</td>
      <td>2011/07/25</td>
      <td>$170,750</td>
    </tr>
    <tr class="bg-white">
      <td>Airi Satou</td>
      <td>Accountant</td>
      <td>Tokyo</td>
      <td>33</td>
      <td>2008/11/28</td>
      <td>$162,700</td>
    </tr>
    <tr class="bg-white">
      <td>Rhona Davidson</td>
      <td>Integration Specialist</td>
      <td>Tokyo</td>
      <td>55</td>
      <td>2010/10/14</td>
      <td>$327,900</td>
    </tr>
    <tr class="bg-dark-grey">
      <td>Brielle Williamson</td>
      <td>Integration Specialist</td>
      <td>New York</td>
      <td>61</td>
      <td>2012/12/02</td>
      <td>$372,000</td>
    </tr>
    <tr class="bg-dark-grey">
      <td>Paul Byrd</td>
      <td>Chief Financial Officer (CFO)</td>
      <td>New York</td>
      <td>64</td>
      <td>2010/06/09</td>
      <td>$725,000</td>
    </tr>
    <tr class="bg-dark-grey">
      <td>Gloria Little</td>
      <td>Systems Administrator</td>
      <td>New York</td>
      <td>59</td>
      <td>2009/04/10</td>
      <td>$237,500</td>
    </tr>
    <tr class="bg-white">
      <td>Jena Gaines</td>
      <td>Office Manager</td>
      <td>London</td>
      <td>30</td>
      <td>2008/12/19</td>
      <td>$90,560</td>
    </tr>
    <tr class="bg-white">
      <td>Haley Kennedy</td>
      <td>Senior Marketing Designer</td>
      <td>London</td>
      <td>43</td>
      <td>2012/12/18</td>
      <td>$313,500</td>
    </tr>
    <tr class="bg-white">
      <td>Tatyana Fitzpatrick</td>
      <td>Regional Director</td>
      <td>London</td>
      <td>19</td>
      <td>2010/03/17</td>
      <td>$385,750</td>
    </tr>
    <tr class="bg-white">
      <td>Michael Silva</td>
      <td>Marketing Designer</td>
      <td>London</td>
      <td>66</td>
      <td>2012/11/27</td>
      <td>$198,500</td>
    </tr>
    <tr class="bg-white">
      <td>Bradley Greer</td>
      <td>Software Engineer</td>
      <td>London</td>
      <td>41</td>
      <td>2012/10/13</td>
      <td>$132,000</td>
    </tr>
  </tbody>
</table>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
  const table = $('#example').DataTable({
    "bLengthChange": false,
    "paging": false,
    "bFilter": false,
    "columnDefs": [
      { "targets": 'no-sort', "orderable": false }
    ],
    "order": []
  });

  // Trigger logic every time the table redraws (after sort, filter, etc.)
  table.on('draw.dt', function() {
    const tbody = $('#example tbody');
    
    // Reset all rows to white first to clear old styles
    tbody.find('tr').removeClass('bg-dark-grey bg-white').addClass('bg-white');

    // Check if we're currently sorting by the Office column
    const sortedColumns = table.order();
    const isSortingByOffice = sortedColumns.length > 0 && $(table.column(sortedColumns[0][0]).header()).hasClass('office');

    if (isSortingByOffice) {
      // Collect unique Office values in the order they appear after sorting
      const officeGroups = [];
      tbody.find('tr').each(function() {
        const officeName = $(this).find('td:eq(2)').text();
        if (!officeGroups.includes(officeName)) {
          officeGroups.push(officeName);
        }
      });

      // Apply grey background to even-positioned groups (1-based = 2nd, 4th, etc.)
      officeGroups.forEach((office, index) => {
        // 0-based index: odd numbers = 1-based even positions
        if (index % 2 !== 0) {
          tbody.find(`tr td:eq(2):contains('${office}')`).closest('tr').removeClass('bg-white').addClass('bg-dark-grey');
        }
      });
    }
  });
});
</script>

What This Does

  1. draw.dt Event Listener: This replaces your header click handler and ensures our background logic runs every time the table updates—even if sorting happens via keyboard shortcuts or other DataTables interactions.
  2. Reset Styles: We start by setting all rows to white to eliminate any leftover background classes from previous states.
  3. Check Sort Column: We verify if the current sorted column is the Office column using DataTables' order() method.
  4. Group & Style Rows: We collect unique Office groups in the sorted order, then apply the grey background to rows in even-positioned groups (2nd, 4th, etc.). This matches your exact requirements:
    • Office Ascending: Groups are Edinburgh (1st), London (2nd), New York (3rd), San Francisco (4th), Tokyo (5th) → London and San Francisco get grey backgrounds.
    • Office Descending: Groups are Tokyo (1st), San Francisco (2nd), New York (3rd), London (4th), Edinburgh (5th) → San Francisco and London get grey backgrounds.

You can remove the xbg-dark-grey class from your CSS now—we don't need it anymore since we're fully resetting styles on each redraw.

内容的提问来源于stack exchange,提问作者Saroj Shrestha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 18:58:19