我目前正在使用以下 JS 代码在侧面创建导航菜单。
$(".side-item-link").on('click', function(e){
e.preventDefault();
var id = $(this).parent().attr('id');
$(this).parent().siblings().removeClass('active');
$(this).parent().addClass('active');
$.ajax({
url : '/' + id + '/only/',
type : 'GET',
success : function(data){
var response = $(data);
$("#content").html(response.filter("#product-block"));
$(".breadcrumb").html(response.filter(".breadcrumbs"));
$("#search").val('');
}
});
history.pushState(null, null, '../' + id);
});
我可以通过单击按钮完美浏览,history.pushState
会相应地更改 URL。但是,我无法使用后退按钮向后导航。如果我按下按钮,则不会加载以前的数据。我该如何解决这个问题?
最佳答案
当您调用 pushState 时,第一个参数是一个状态对象。
来自 MDN:
var stateObj = { foo: "bar" }; history.pushState(stateObj, "page 2", "bar.html");
您应该传入一个包含页面状态的对象,而不是 null
。
然后,listen for a popstate event :
addEventListener("popstate", function (event) {
console.log(event.state);
})
事件触发会告诉您用户已经浏览了历史记录。 event.state
的值将包含您使用 pushState
为他们将要访问的页面添加的数据。您可以使用它来将 DOM 恢复到该状态。
关于javascript - 如何在使用 HTML History API 时使用后退按钮导航网站?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33799453/