在DataTables的背景下,如何获取已排序行的索引?
我有一个分页、可排序、可过滤的表格,其中列4
(即第五列)包含消息号。我正在编写一个函数,它将当前页面切换到显示该消息编号的页面,并突出显示包含该条目的行。它看起来像这样:
var currentHighlight = null;
function goToMessageNumber(number) {
var table = $('#messages').DataTable();
// remove current highlight
if (currentHighlight) {
$(table.row(currentHighlight).nodes()).removeClass('highlight');
}
// find the row we need
var index = table.column(4).data().indexOf(''+number);
if (index === -1) {
return;
}
currentHighlight = index;
// add new highlight
$(table.row(currentHighlight).nodes()).addClass('highlight');
// go to page
var page = Math.floor(currentHighlight / table.page.len());
table.page(page).draw(false);
}
如果表处于初始排序顺序,则效果非常好。但是,当应用过滤器或排序时,此操作会失败。这里有什么简单的解决方案?
最佳答案
您可以迭代 every()
当前行{ search: 'applied' }
order,通过它计算出您要查找的值所在的当前页面。以下是查找特定名称的说明性示例:
$('#goto').on('click', function() {
var page, data, count = 0;
table.rows( { search: 'applied' } ).every(function(rowIdx, tableLoop, rowLoop) {
count ++
data = this.data()
if (data[1] == 'Airi Satou') {
page = Math.floor(count / table.page.len())
table.page( page ).draw('page')
return
}
})
})
演示 -> http://jsfiddle.net/1o3fLcqy/
上面跳转到Airi Satou
的页面位于,无论排序/过滤如何(假设 Airi Satou
存在于当前行中)。对第 5 列中的消息编号执行相同的操作。
关于操作行/<tr>
, rowIdx
保存原始索引。所以你可以这样做:
table.row(rowIdx).nodes().to$().addClass('highlight')
关于javascript - 获取排序行的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37773981/