You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataTables恢复升序后再次点击同列重复升序问题求助

问题:DataTables恢复升序排序后点击同一列无法切换排序

我在使用history.pushState/history.replaceState实现以下功能:用户每次点击表格表头th时,保存开启了serverSide处理且orderMulti设为false的表格排序状态,后续通过.on("popstate")事件恢复保存的排序。

整体运行正常,但存在一个问题:当恢复的排序为升序时,用户再次点击同一列会触发二次升序排序(表格重绘但排序结果无变化);而恢复的排序为降序时,再次点击同一列则能正常切换为升序。

保存排序状态的代码

setTableState = function() {
    let state = history.state || {}, url = "/"+location.pathname.split("/")[1]+"/",
        order = myTable.order();
    
    if (order.length && order[0][1]) {
        state["sort"] = [{
            name: myTable.columns(order[0][0]).init()[0].name,
            dir: order[0][1],
        }];
        url += "sort:" + (state["sort"]["dir"] == "desc" ? "-" : "") + state["sort"]["name"] + "/";
    }
    else state["sort"] = [];
    
    if (url == location.pathname) history.replaceState(state, ""); // Prevent duplication of history item
    else history.pushState(state, "", url);
}

保存与恢复排序的代码

$(document).ready(function() {
    myTable.on("draw", function() {
        setTableState();
    });

    $(window).on("popstate", function(e) {
        if (history.state && "sort" in history.state && history.state["sort"].length) {
            myTable.order(history.state["sort"]).draw();
        }
        else myTable.order(defaultSort).draw();
    });
});

想问下这是DataTables自身的Bug吗?

内容的提问来源于stack exchange,提问作者bur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 05:36:09