使用带有history.pushstate和popstate的后退按钮时如何触发更改?

Rwd*_*Rwd 46 javascript html5 back-button pushstate

当涉及到js时,我几乎是一个新手,所以如果我遗漏了一些非常简单的话,我很抱歉.

基本上,我已经做了一些关于使用history.pustate和popstate的研究,我已经做了,所以通过使用查询字符串添加到url(?v=images)或(?v=profile)...(v意思是"视图")的末尾这个:

var url = "?v=profile"
var stateObj = { path: url };
history.pushState(stateObj, "page 2", url);
Run Code Online (Sandbox Code Playgroud)

我想这样做,所以我可以将内容加载到div但不重新加载我使用该.load()功能完成的页面.

然后我使用了这段代码:

$(window).bind('popstate', function(event) {
    var state = event.originalEvent.state;
Run Code Online (Sandbox Code Playgroud)

$(document).ready()部分和后来尝试只是<script>标签,但都没有工作.

我不知道如何制作它,所以当我使用后退按钮时内容会发生变化,或者至少让它变为可以触发我自己的功能; 我假设它与状态对象有关?!我似乎无法在网上找到任何清楚解释过程的内容.

如果有人可以帮助我,那将是惊人的,并提前感谢任何人!

pim*_*vdb 52

popstate当有一个状态时,唯一包含状态.

当它像这样:

  1. 初始页面加载
  2. 新页面加载,状态添加通过 pushState
  3. 按下后退按钮

然后没有状态,因为初始页面是定期加载的,而不是pushState.其结果是,该onpopstate事件与烧制statenull.所以当它是null,它意味着应该加载原始页面.

您可以实现它,这history.pushState将被一致地调用,您只需要提供这样的状态更改函数:单击此处查看jsFiddle链接

function change(state) {
    if(state === null) { // initial page
        $("div").text("Original");
    } else { // page added with pushState
        $("div").text(state.url);
    }
}

$(window).on("popstate", function(e) {
    change(e.originalEvent.state);
});

$("a").click(function(e) {
    e.preventDefault();
    history.pushState({ url: "/page2" }, "/page2", "page 2");
});

(function(original) { // overwrite history.pushState so that it also calls
                      // the change function when called
    history.pushState = function(state) {
        change(state);
        return original.apply(this, arguments);
    };
})(history.pushState);
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你帮助@pimvdb,甚至更多,非常快速回复.祝一切顺利. (2认同)

Jiř*_*ník 10

也许这不是最佳解决方案,也许它不适合您的需求.但对我来说,最好重新加载页面.因此页面是一致的,它根据当前的查询字符串加载所有内容.

$(document).ready(function() {
    $(window).on("popstate", function (e) {
        location.reload();
    });
});
Run Code Online (Sandbox Code Playgroud)