[英]How to manipulate browser history and catch browser back/forward buttons?
I've been searching for couple of hours now trying to make a simple browser history manipulation. 我一直在搜索几个小时,试图进行简单的浏览器历史记录操作。
I have a couple of menu links and I bind click handlers to them. 我有几个菜单链接,并将单击处理程序绑定到它们。 Links' href's are just hashes:
href="#Home"
or href="#About"
. 链接的href只是散列:
href="#Home"
或href="#About"
。
I would like to display a subpage when user clicks on link, without page reload and change the browser url. 当用户单击链接时,我想显示一个子页面,而无需重新加载页面和更改浏览器URL。
I've also tried this basic example with pushState() but it doesn't work: http://jsbin.com/wecubizovu/1/edit?html,js,console 我也用pushState()尝试了这个基本示例,但是它不起作用: http ://jsbin.com/wecubizovu/1/edit?html,js,console
http://jsbin.com/wecubizovu http://jsbin.com/wecubizovu
When I run this in Chrome, I expect that, if user clicks on the link, he'll have #asd appended to url and popstate won't change . 当我在Chrome中运行此代码时,我希望如果用户单击链接,他将在URL后面附加#asd并且popstate不会改变 。 Why is popstate being triggered?
为什么会触发popstate? How can I make it so that when user clicks on a link, I append hash to browser url and when user clicks browser back button, I catch that event and display the piece of page that I want?
如何做到这一点,以便当用户单击链接时,将哈希附加到浏览器URL,当用户单击浏览器后退按钮时,我捕获该事件并显示所需的页面?
Thanks! 谢谢!
Your a
element has a href
of ''
which is still executed if you do not prevent the default action and this somehow messes up what you want to do. 您
a
元素的href
值为''
,如果您不阻止默认操作,该href
仍然会执行,从而以某种方式弄乱了您想要执行的操作。 Changing your function to 将功能更改为
$("#asd").click(function(e) {
e.preventDefault();
alert("jo");
window.history.pushState("", document.title, "#asd");
});
achieves what you are looking for. 实现您想要的。
EDIT: Links: http://jsbin.com/sosozeteti 编辑:链接: http : //jsbin.com/sosozeteti
http://jsbin.com/sosozeteti/1/edit?html,js http://jsbin.com/sosozeteti/1/edit?html,js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.