首页 > 解决方案 > column().data() 与正交数据而不是显示?

问题描述

column().data()用来获取列中所有值的数组。它适用于纯文本单元格,但从包含 HTML 的单元格中,我得到了完整的 HTML。考虑以下示例中的Office ,改编自live.datatables.net

$(document).ready( function () {
  var table = $('#example').DataTable();
  console.log(table.column(2).data().toArray());
} );
<!DOCTYPE html>
<html>
  <head>
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

    <link href="//nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="//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>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
          </tr>
        </thead>

        <tbody>
          <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td data-value="GB"><b>GB</b><i>Edinburgh</i></td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$3,120</td>
          </tr>
          <tr>
            <td>Ashton Cox</td>
            <td>Technical Author</td>
            <td data-value="US"><b>US</b><i>San Francisco</i></td>
            <td>66</td>
            <td>2009/01/12</td>
            <td>$4,800</td>
          </tr>
        </tbody>
      </table>
    </div>
  </body>
</html>

控制台输出:

[
  "<b>US</b><i>San Francisco</i>",
  "<b>GB</b><i>Edinburgh</i>"
]

但是我如何使该调用返回例如"US"而不是"<b>US</b><i>San Francisco</i>"

根据/manual/data/orthogonal-datadisplay ,过滤和排序功能已经存在类似的问题(即必须将机器可读的值保留在人类友好的值旁边),并使用data-*属性解决。

例如考虑货币数据;为了显示,它可能以货币符号和千位分隔符的格式显示,而排序应该以数字方式进行,并且对数据的搜索将接受任何一种形式。

所以我想我的问题的解决方案可能是一些data-value属性,但我没有找到任何东西。可行吗?

标签: datatables

解决方案


我最终得到的代码更加通用(因此不仅适用于国家和支持innerText),但它完全基于@andrewjames 的回答,这是应得的。

var values = Array.from(
    table.column(2).nodes(),
    function(cell) {
        // First, look for the dedicated attribute
        if (cell.hasAttribute('data-filter')) {
            return cell.getAttribute('data-filter');
        }
        // Otherwise, use the inner text of the table cell
        return cell.innerText;
    }
);

推荐阅读