5

我正在使用 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");
        }
    });
});

但不是这个,我想为前向和后向 ID 创建两个单独的数组,因此当触发返回时,我可以在“返回”数组中获取最后一个帖子 ID 以获得我需要的内容。

我的问题是如何在 popstate 上检测向前或向后以实现这一点,或者通常是一种更好的方法来实现这一点。

$(window).on('popstate', function(event) {
 <---detect direction---->
}); 
4

0 回答 0