Javascript 添加到浏览器历史记录而无需重新加载页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10541388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add to browser history without page reload
提问by twiz
Basically, I have a page that contains a form. When a user submits that form, a Javscript function is called and the user is dynamically presented with a new form.
基本上,我有一个包含表单的页面。当用户提交该表单时,会调用一个 Javscript 函数,并动态地向用户呈现一个新表单。
At this point, what I would like is for the user to be able to click the browser's back button and be taken back to the first form. Is this possible?
在这一点上,我希望用户能够单击浏览器的后退按钮并返回到第一个表单。这可能吗?
Thanks for the quick responses, but I am having trouble getting pushState to work. The HTML still displays "second form" after I click the back button.
感谢您的快速回复,但我无法让 pushState 正常工作。单击后退按钮后,HTML 仍显示“第二个表单”。
Here is the code I used to test it:
这是我用来测试它的代码:
<script>
function newPage(){
history.pushState({state:1}, "State 1", "?state=1");
document.getElementById('formBox').innerHTML="second form";
}
</script>
<input type="button" onclick="newPage();" value="forward" />
<div id='formBox'>first form</div>
回答by Elliot Bonneville
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Relevant link to the docs.
回答by Michael Robinson
I've accomplished similar behaviour with the HTML5 History/State APIs, using History.js, described thus:
我已经使用 HTML5 History/State API 完成了类似的行为,使用History.js,描述如下:
Provide a cross-compatible experience for all HTML5 Browsers (they all implement the HTML5 History API a little bit differently causing different behaviours and sometimes bugs - History.js fixes this ensuring the experience is as expected / the same / great throughout the HTML5 browsers)
为所有 HTML5 浏览器提供交叉兼容的体验(它们都以稍微不同的方式实现 HTML5 历史 API,导致不同的行为,有时还会出现错误 - History.js 修复了这个问题,确保整个 HTML5 浏览器的体验如预期/相同/很棒)
Example:
例子:
History.pushState({state:1}, "State 1", "?state=1");