使用 Javascript 处理浏览器后退按钮/使用锚点可以采用不同的方法吗?
我目前正在努力使用 Ajax 调用和不显眼的 JS 在网站上实现良好的导航。我正在捕获链接上的点击事件,加载内容,将其附加到 div,然后返回 false。这非常有效,并且还允许 Google 使用语音 URL 抓取网站。
但我不知道如何处理浏览器后退按钮。我找到了这个解决方案来捕获用户单击后退按钮时的事件:
http://www.bajb.net/2010/02/browser-back-button-detection/
它工作得很好。但我也希望当用户通过链接找到网站并想要返回上一页时后退按钮能够正常工作(我不想陷阱任何人)。
当我想到最好的方法是使用锚点。普通后退按钮支持它们,您可以返回历史记录而无需重新加载页面(/#1 <- /#2 <- /#3 等)。
它的工作方式如下:
- 在链接中使用普通 URL,但是捕获点击事件
- 当用户点击时,加载内容并将其附加到 DIV
- 使用锚点更改 window.location(例如 'domain.com/#products/women-clothing' 和 window.location="#products/women- 当 window.location 更改时,获取锚点,读出路径并通过 ajax获取
- 内容,将其附加到 DIV
只有最后一部分对我来说不太清楚,我可能需要帮助。
最后,我的问题是:这有意义吗?
谢谢!
I'm currently struggling with a good navigation on a website using Ajax calls and unobstrusive JS. I'm catching the click event on links, load the content, attach it to a div and then return false. This works quite well and also allows Google to crawl the site with speaky URLs.
But I didn't know how to deal with the browser back button. I found this solution to catch the event when the user clicks on the back button:
http://www.bajb.net/2010/02/browser-back-button-detection/
It works quite well. But I also want the back button to work normally when the user found the website via a link and wants to return to the previous page (I don't want to trap anyone).
When I thought about it the best way would be to use anchors. The normal back button supports them and you can go back in history without reloading the page (/#1 <- /#2 <- /#3 etc.)
It would work like this:
- Use normal URLs in the link, but catch the click event
- When user clicks, load content and attach it to a DIV
- Change the window.location, using an anchor (e.g. 'domain.com/#products/women-clothing' with window.location="#products/women-clothing";)
- When the window.location changes, get the anchor, read out the path and get the content via ajax, attach it to a DIV
Only the last part isn't really clear for me and I could need help here.
Finaly, my question: Does this make any sense?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将内容加载到
div
后,将href
添加到window.location.hash
即可。然后,您可以使用后退按钮检测脚本来加载哈希中的内容。Just add the
href
towindow.location.hash
after loading the content into adiv
. Then you can use that back button detection script to load what ever is in the hash.我通过使用这个很棒的 jQuery 插件解决了这个问题: History.js
谢谢!
I solved the problem by using this great jQuery Plugin: History.js
Thanks!