从 url 中检索特定哈希标签的值
在原始 Javascript 中,如何检查 url 中是否存在特定的哈希标签,然后获取该值?
示例: http://www.example.com/index.html# hashtag1=value1&#hashtag2=value2
我希望能够获取 hashtag1 或 hashtag2 的值。
In raw Javascript, how would one go about checking that a specific hash tag exists in a url, then grab the value?
Example: http://www.example.com/index.html#hashtag1=value1hashtag2=value2
I want to be able to grab the value of either hashtag1 or hashtag2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用:
检查“哈希键”是否存在:
获取哈希键的值:
设置哈希键的值,并更新 URL 哈希:
从 URL 中删除哈希键:
将哈希值重新加载到本地对象中:
将当前键值集推送到 URL 哈希值:
请注意,当某个键不存在并且您尝试
获取
它时,它将返回未定义.但是,键可能没有值,例如
#key=val&novalue
,其中 novalue 是没有值的键。如果您执行HashSearch.get("novalue")
,它也会返回undefined
。在这种情况下,您应该使用HashSearch.keyExists("novalue")
来验证它确实是一个键。Using it:
Check if a "hash key" is present:
Get the value for a hash key:
Set the value for a hash key, and update the URL hash:
Remove a hash key from the URL:
Reload the hash into the local object:
Push the current key value set to the URL hash:
Note that when a key does not exist and you try to
get
it, it will returnedundefined
. However, a key could exist with no value -- for example#key=val&novalue
where novalue is a key with no value. If you doHashSearch.get("novalue")
it would also returnundefined
. In which case, you should useHashSearch.keyExists("novalue")
to verify that it is indeed a key.我用这个,它对我来说效果很好。我相信这是对我在某处拾取的一句台词的一点调整。
I use this, and it works just fine for me. It's a little adjusing to a line I picked up somewhere, I believe on SO.
window.location.hash
应该给你你想要的。window.location.hash
should give you what you want.jQuery BBQ(后退按钮和查询)利用 HTML5 hashchange 事件来实现简单但又强大的可书签#hash 历史记录。此外,jQuery BBQ 提供了完整的 .deparam() 方法,以及哈希状态管理以及片段/查询字符串解析和合并实用程序方法。
简而言之:该库允许您动态更改页面内的哈希“查询字符串”并进行 URL 匹配。它还允许您动态提取值并规范化“查询字符串”的使用。最后,它将查询字符串添加到历史记录中,这允许后退按钮充当先前查询哈希值之间的导航。
对于用户体验来说,一个好的举措是查看像 jQuery BBQ 这样的库:)
jQuery BBQ (back button and query) leverages the HTML5 hashchange event to allow simple, yet powerful bookmarkable #hash history. In addition, jQuery BBQ provides a full .deparam() method, along with both hash state management, and fragment / query string parse and merge utility methods.
In short: This library allows you to dynamically change a hash "query string" within your page and have the URL match. It also allows you to dynamically pull values and normalizes working with the "query string." Finally it will add the query strings into the history which allows the back button to function as a navigation between previous query hash values.
A good move for UX would be to check out a library like jQuery BBQ :)