我的项目中有多个数据表问题。这是代码:
HTML:
<table id="dt">
<thead>
<tr>
<th>Index</th>
<th>Some headline</th>
</tr>
</thead>
<tbody>
<tr>
<td data-href="http://localhost/linkforid/1">1</td>
<td>Some information</td>
</tr>
</tbody>
</table>
JavaScript:
const table = $('#dt').DataTable({
'columnDefs': [
{'targets': [0], 'visible': false}
],
stateSave: true,
stateDuration: 0
});
$(document).on('click', '#dt tbody tr', function () {
let td = table.row(this).data()[0];
//get data-href attribute???
});
所以这是我的问题
首先首先我想打开第一个提供的链接<td>
每当我点击一行。对于这种情况,我尝试使用 table.row(this).data()[0]
(请记住 <td>
是隐藏的!),但这只会返回文本(在本例中为数字/索引 1)。
如何访问隐藏 <td>
元素并检索 data-href
属性?
第二个问题:我正在使用 stateSave
选项并将其保存到 localStorage (stateDuration:0)
.现在我注意到,每当我对表格进行更改时(例如隐藏/取消隐藏列)。更改实际上从未发生,因为它从 localStorage
中提取表信息.
如何在每次进行更改时强制更新我的表架构?使用 stateSave
时有没有办法忽略表列(可见:true/false) ?
第二个问题的解决方案:
const table = $('#dt').DataTable({
'columnDefs': [
{'targets': [0], 'visible': false}
],
stateSave: true,
stateDuration: 0,
stateSaveParams: function (settings, data) {
data.columns.forEach(function (column) {
delete column.visible; //exclude what you dont want
});
}
});
请随意也只回答 1 个问题。我真的很清楚这个问题并且没有可能的解决方案。谢谢
最佳答案
隐藏的列从 dom 中移除。您可以添加 href
值作为 <tr>
的属性节点本身,或通过 API:
$(document).on('click', '#dt tbody tr', function () {
const href = table.cell({ row: 0, column: 0, order: 'original' }).node().getAttribute('data-href')
console.log(href) //will always output http://localhost/linkforid/1
})
您可以添加 to$()
至 nodes()
并定位 <tr>
节点作为 jQuery 实例。顺便说一句,
$('#dt').on('click', 'tbody tr', function() {
会快得多,因为代码不必每次都从第一个节点开始遍历 dom。
关于javascript - DataTables:获取隐藏的 td 元素并强制更新 stateSave,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59405985/