使用jQuery更改html内容后使用浏览器后退按钮

时间:2018-04-25 09:51:23

标签: javascript jquery html back-button

我在单击链接时使用jQuery更改div的html内容。

<a href="#1" class="navclick" data-content="1">1</a>
<a href="#2" class="navclick" data-content="2">2</a>
<a href="#3" class="navclick" data-content="3">3</a>

所以单击我的jQuery代码更改html内容。 有没有办法让浏览器返回按钮再次工作并在点击它时更改内容?它确实改变了网址,但当然它没有改变内容从f.e.单击后退按钮时#3到#1。

到目前为止我找到的libs已经过时了。目前最好的方法是什么?

谢谢!

编辑:

这就是我在内容div中加载内容的方式:

$('#content').hide().load($content+".html" , function(){
        $('#content').fadeIn('slow');
        var stateObj = { foo: $content };
        history.pushState(stateObj, $content, $content+".html");
        console.log(history);
    });

1 个答案:

答案 0 :(得分:0)

是的确有。更改html内容后,请执行pushstate。

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

现在这会将bar.html推送到您的网址,所以当您点击它时它不会离开当前网站,但“只是”回到历史记录中。

您可以像这样点击后退按钮:

$(window).on("popstate", function(e) {
  alert("Pressed back or forward");
});

请注意,popstate会向后和向前点击。所以你需要一种方法来检查用户是否向后点击。但我会把它留给你; - )