如何将orderCells设置为数据表的中间行?

时间:2019-01-12 12:36:48

标签: javascript jquery datatables datatables-1.10

我正在使用DataTables。我希望将排序链接到第二个跨度行,这意味着排序是在 Name 单元格而不是 Dummy 上启用的。

代码:

$(document).ready(function () {
  var table = $('#example').DataTable({
    orderCellsTop: true, //move sorting to top header
  });
});

HTML:

<table id="example" class="display nowrap" width="100%">
    <thead>
      <tr>
        <th>Dummy</th>
      </tr>
      <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
      <tr>
        <th>Name1</th>
        <th>Position1</th>
        <th>Office1</th>
        <th>Age1</th>
        <th>Start date1</th>
        <th>Salary1</th>
      </tr>
    </thead>
    .....

这里是live demo

1 个答案:

答案 0 :(得分:1)

您可以做一些调整

  • 向{strong> Dummy 标头添加colspan=2

    <th colspan="2">Dummy</th>
    
  • 现在在 Name Name1 标头之后添加一个空标头:

    <th>Name</th>
    <th></th>
    
  • 同样,将空列添加到名称列旁边的每一行:

    <td>Tiger Nixon</td>
    <td></td>
    
  • 最后,在DataTables初始化中添加columnDefs选项:

    columnDefs: [{ 
      visible: false, 
      targets: 1 
    }]
    

最终代码如下:

$(document).ready(function() {
  var table = $('#example').DataTable({
    orderCellsTop: true,
    columnDefs: [{
      visible: false,
      targets: 1
    }]
  });
});
<!DOCTYPE html>
<html>

<head>
  <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

  <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
  <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>

  <meta charset=utf-8 />
  <title>DataTables - JS Bin</title>
</head>

<body>
  <div class="container">
    <table id="example" class="display nowrap" width="100%">
      <thead>
        <tr>
          <th colspan="2">Dummy</th>
        </tr>
        <tr>
          <th>Name</th>
          <th></th>
          <th>Position</th>
          <th>Office</th>
          <th>Age</th>
          <th>Start date</th>
          <th>Salary</th>
        </tr>
        <tr>
          <th>Name1</th>
          <th></th>
          <th>Position1</th>
          <th>Office1</th>
          <th>Age1</th>
          <th>Start date1</th>
          <th>Salary1</th>
        </tr>

      </thead>

      <tbody>
        <tr>
          <td>Tiger Nixon</td>
          <td></td>
          <td>System Architect</td>
          <td>Edinburgh</td>
          <td>61</td>
          <td>2011/04/25</td>
          <td>$3,120</td>
        </tr>
        <tr>
          <td>Garrett Winters</td>
          <td></td>
          <td>Director</td>
          <td>Edinburgh</td>
          <td>63</td>
          <td>2011/07/25</td>
          <td>$5,300</td>
        </tr>


      </tbody>
    </table>
  </div>
</body>

</html>