如何获取搜索内容的默认页码?

问题描述

我正在使用 DataTables用户创建的笔记表进行排序、分页搜索。我们有一个通知/ping 系统,用户可以在其中标记笔记以供审核,收件人将收到通知,说明有笔记需要他们注意。

用户点击通知时,他们被带到带有笔记表的页面,并使用一些 jquery,页面向下滚动到标记的笔记并突出显示它。这很有效,但有一个例外。

问题

由于 DataTables 的认排序,如果标记的笔记有点旧并且没有出现在分页结果的第 1 页上,我的“滚动到视图”jquery 不起作用,因为 DataTables 从HTML。

目标

我想要做的是在页面加载时搜索标记的行,并在运行跳下页面并突出显示该行的代码之前自动跳转到表格中的该页面。我知道我可以使用 search() 查找特定内容,使用 page() 跳转到特定页面,但 DataTables 是否可以让我确定我搜索内容位于哪个页面(假设认排序)?

解决方法

根据@andrewjames 的评论,我查看了 jumpToData() 插件,这正是我所需要的。插件代码非常简单:

jQuery.fn.dataTable.Api.register('page.jumpToData()',function (data,column) {
    var pos = this.column(column,{ order: 'current' }).data().indexOf(data);

    if (pos >= 0) {
        var page = Math.floor(pos / this.page.info().length);
        this.page(page).draw(false);
    }

    return this;
});

您只需调用 page.jumpToData() 函数,传入您要查找的数据以及您想在哪个列中找到它,它就会自动跳转到该页面。

我的代码最终看起来像这样:

    var table = $('#noteTable').dataTable().api();

    if (table.row('.myTarget').data()) {
        // Need to identify unique content in the note we're trying to jump to.
        // The timestamp should work for that
        var timeColumn = 1;
        var timestamp = table.row('.myTarget').data()[timeColumn];

        // Jump to the page the flagged note is on
        table.page.jumpToData(timestamp,timeColumn);

        var flaggedNote = document.getElementsByClassName('myTarget')[0];

        //scroll down the page and highlight the row to make it stand out
        flaggedNote.scrollIntoView();
        flaggedNote.classList.add('highlight');
    }
    else {
        DisplayError("Unable to locate the requested notification.");
    }