在 popstate 上检测向前或向后

use*_*979 5 ajax pushstate popstate

我使用 ajax 将新的帖子页面加载到我网站的内容部分,并使用 Pushstate 每次编辑 url。我正在寻找一种在浏览器上单击前进和后退按钮时移动的方法。

我的想法是创建一系列帖子 ID,每次前进时都会向列表中添加一个

$(document).on("click", ".title[data-ajax='post']", function() {
    $post_id = $(this).data("id");
    $post_type = $(this).data("type");
    $post_url = $(this).data("url");
    var historyData = $(".wrapper").attr("data-history");
    if (!historyData){
        historyData = [];
    }
    else{
        historyData = JSON.parse(historyData);
    }
    historyData.push({
      id: $post_id,
      type: $post_type,
      url: $post_url
    });
    var data = {
        action : 'new_ajax_'+ $post_type +'_template',
        post_id : $post_id
    };
    $("#main").empty().hide();
    $.ajax({
        url : ajax_object.ajax_url,
        type : 'post',
        data : data,
        success: function(html) {
            $("#main").append(html);
            history.pushState('data', '', $post_url);
            $(".wrapper").attr("data-id", $post_id);
            $(".wrapper").attr("data-history", JSON.stringify(historyData));
            $("#main").fadeIn("fast");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

但我不想为前向和后向 id 创建两个单独的数组,这样当触发后向时,我可以获取“后向”数组中的最后一个帖子 id 来获取我需要的内容。

我的问题是如何检测 popstate 的前进或后退以实现此目的或实现此目的的更好方法。

$(window).on('popstate', function(event) {
 <---detect direction---->
}); 
Run Code Online (Sandbox Code Playgroud)