用户单击同一链接时,Hashchange不触发 [英] Hashchange not firing when user clicks on same link
问题描述
我正在创建一个HTML和Javascript客户端,以便在与REST API对话的浏览器中运行.我正在使用 RouteMap 设置我的URL.所以我遵守了这样的约定
http://mysite.com/#/{ResourceName}/[edit|view|list]/[Id]/
我只设置了一条路由,并且在绑定到hashchange的函数中获取了这些参数.大多数事情都可以正常工作.仅有两个问题,我因这些问题而陷入困境.
- 如果用户单击同一链接两次,则不会触发hashchange事件.是的,哈希值没有改变,因此显然不会触发.但是应该可以做些什么,我很想念.
- 如果我在UI中更改了一些我不想更改哈希链接的内容(例如调出新的div并隐藏了一些内容),则会丢失该历史记录,并且无法通过正确单击后退按钮来返回.
任何帮助将不胜感激.
对于#1,您可能希望将处理程序附加到链接单击事件.这样,您可以知道是否单击了链接.当我使用onhashchange时,我总是在click事件上附加一些内容,以帮助polyfills进行onhashchange,因此至少我可以知道它何时失败.
对于#2,我想指出的是,使用自动内容来更改用户的历史记录是有问题的.您可以用无意义的哈希变化填充某人的历史记录.我建议仅在用户实际交互时更改历史记录.简而言之,HTML5确实提供了pushState
和popState
. 参考
I'm creating an HTML and Javascript client for running in browser which talks to REST API. I'm using RouteMap to set my URLs. So I've kept a convention something like this
http://mysite.com/#/{ResourceName}/[edit|view|list]/[Id]/
I've set just one route and I'm grabbing these parameters in the function bounded to hashchange. Most of the things work fine. Just two issues and I'm stuck because of them.
- If the user clicks on the same link twice, hashchange event doesn't fire. Yes, hash has not changed so obviously it won't fire. But there should be something which can be done and I'm missing that.
- If I change something in the UI (like bring up new divs and hide some) for which I don't want to change the hash link, I loose that history and can't go back by clicking the back button properly.
Any help will be grateful.
For #1, you probably want to attach a handler to the link click event. That way you can tell if the link is being clicked. When I use onhashchange, I always attach something to the click event to assist polyfills for onhashchange, so at least I can tell when it's failing.
For #2, I want to point out that having automatic stuff change the user's history is problematic. You could fill someone's history with minute, meaningless hash changes. I recommend only changing the history when the user actually interacts. Short of that, HTML5 does offer pushState
and popState
. Reference
这篇关于用户单击同一链接时,Hashchange不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!