48

当谈到 js 时,我几乎是一个新手,所以如果我错过了一些非常简单的东西,我很抱歉。

基本上,我已经对使用 history.pustate 和 popstate 进行了一些研究,并且我已经做到了,因此通过使用将查询字符串添加到 url ( ?v=images) 或 ( ?v=profile)...(v意思是“视图”)的末尾这:

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

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

然后我使用了这段代码:

$(window).bind('popstate', function(event) {
    var state = event.originalEvent.state;

$(document).ready()部分中,后来在<script>标签中尝试过,但都没有奏效。

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

如果有人可以帮助我,那就太棒了,并提前感谢任何这样做的人!

4

2 回答 2

56

只有当popstate有一个状态时才包含一个状态。

当它是这样的:

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

然后没有状态,因为初始页面是定期加载的,而不是pushState. 结果,该onpopstate事件以stateof触发null。所以当它是时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);
于 2011-11-07T15:45:54.813 回答
20

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

$(document).ready(function() {
    $(window).on("popstate", function (e) {
        location.reload();
    });
});
于 2018-02-22T10:26:25.357 回答