datatables - 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
属性,但我没有找到任何东西。可行吗?
解决方案
我最终得到的代码更加通用(因此不仅适用于国家和支持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;
}
);
推荐阅读
- google-kubernetes-engine - 有没有办法访问 Istio 在 GKE 中创建的 promsd 服务?
- json - 如何绕过 Nodebb 中先前声明的 json body-parser?
- reactjs - 如何使用基于条件的映射函数循环数组然后设置状态?
- hadoop - 在 Hadoop 中,如何验证我是否对 DFS 传输进行了数据加密?
- data-structures - 均衡四叉树单元的大小
- swiftui - SwiftUI:删除模型时如何弹出详细视图
- firebase - 用户只能有一个用户属性值吗?
- java - 递增 ArrayList 时出现 IndexOutOfBoundsException
- xaml - Xamarin Forms 将 ImageSource 绑定到元素内的元素
- javascript - ReCaptcha3:当用户采取行动时如何调用执行?