首页 > 解决方案 > 如何将 orderCells 设置为数据表的中间行?

问题描述

我正在使用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>
    .....

这是一个现场演示

标签: javascriptjquerydatatablesdatatables-1.10

解决方案


你可以做一些调整

  • 添加colspan=2虚拟标题:

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

    <th>Name</th>
    <th></th>
    
  • 同样,在Name列旁边的每一行中添加一个空列:

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

    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>


推荐阅读