AJAX 后退按钮

AJAX back button

我一直在阅读有关 history.pushStatepopstate 的内容,但对于一个填充了大部分 AJAX 请求的网页(比如允许用户向其中添加项目的书店)购物车),是否有一个带有 history 对象或类似东西的函数可以倒回这些​​添加?

下面的示例对此进行了更简单的表示。用户单击 div,"Shown" 出现在相应的 div 中。在这些 div 下方是文本 You have selected [detail]。这会根据选择发生变化,并触发 popState 以正确的方式更改文本。

但是 div 仍然有 "Shown"。有没有一种方法可以按照添加它们的顺序删除它们,类似于文本行的更改方式,或者我是否必须创建一个单独的函数来处理这个问题——这与添加 [=26 的函数相反=] 到 div?

我已经添加了一些我编辑过的功能来实现上述目标,但我只是不喜欢它的复杂程度。

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>

<div class='name'></div>
<div class='age'></div>
<div class='sex'></div>

<p>You have selected <span>no color</span></p>

</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>

<script>

$('div').on('click', function() {

var detail = $(this).attr('class');

showDetails(detail);
doPushState(detail);

});

function showDetails(detail) {
var classDeets = '.'+detail

$(classDeets).text("Showing " + detail);
$('p span').text(detail);

}

function doPushState(detail) {

var state = { selected : detail },
  title = "Page title",
  path = "/" + detail;

  history.pushState(state, title, path);
}

function removeDetails(detail) {

var classDeets = '.'+detail

$(classDeets).text("");
}

function checkState(detail) {

var temp = document.getElementsByClassName(detail)[0].innerHTML;

if(temp.length == 0){
  showDetails(detail);
}
else{
  removeDetails(detail);

 }

}

$(window).on('popstate', function(event) {

var state = event.originalEvent.state;

if (state) {
  checkState(state.selected);
}
});

</script>

没有更多上下文,很难重写代码。也就是说,您需要使用 history.replaceState() 而不是 history.pushState().

history.replaceState() 修改 历史条目的状态。 From MDN:“replaceState() 在您想要更新状态对象或 URL 当前历史条目以响应某些用户操作时特别有用。”

我不确定您的具体用例是什么,但我立即想到了我所做的 ajax 加载报告和列表页面。我在“#”之后对报告的选项进行编码。它使浏览器按钮按预期工作以基于 url 进行更新,并使其对其他人 link 可用。然后你只需要轮询 # 编码的数据来检测变化并相应地更新。由于您使用 #(在页面 link 中),它不会触发页面加载到服务器。您只需确保,如果您使用编码的哈希数据,您不会使用页内 links 进行页面导航。如果这听起来像一个选项,请告诉我,我可以 post 一些帮助代码来设置它。