简体   繁体   English

使用jQuery从URL中的哈希获取值

[英]Get values from hash in URL using jquery

If I re-rite the URL using : 如果我使用以下网址重新发送网址:

var id = 150
window.location.hash = "id="+id;

how to get the value of id using jQuery ? 如何使用jQuery获取id的值?

No jQuery needed.. 不需要jQuery。

var id = /^#?id=(.+)/.exec(location.hash);
id = id ? id[1] : '';
// OR
var id = location.hash.substr(4);  // (when hash can only be #id=..)
                                   // This also selects 123 in #no=123 (!)  

+1 for Rob W 's answer not to use jQuery for this. +1为Rob W的答案不为此使用jQuery。 But there're two things, i'd like to point out. 但是有两件事我想指出。

1.) Executing a regular expression, plus using a tertiary operator is "overload" , too. 1.)执行正则表达式,以及使用三级运算符,同样也是“重载” ;-) ;-)
2.) You should consider that some browers return the hash symbol, and some don't! 2)您应该考虑一些浏览器返回哈希符号,而有些则不!

To avoid to truncate the actual value part, I'd say it's safer to use replace() , instead of substr() : 为了避免截断实际值部分,我想说使用replace()而不是substr()更安全:

var id = location.hash.replace('id=', '').replace('#', '');

UPDATE: 更新:
I think split() is an even better solution: 我认为split()是一个更好的解决方案:

var id = location.hash.split('id=')[1];

Just one (native) function call, which also "checks" if the request URL actually contains a hash that contains the string "id=idString" . 仅一个(本机)函数调用,如果请求URL实际上包含包含字符串 "id=idString" 的哈希,则该函数还“检查 "id=idString"

If it does, the value of var id is "idString" . 如果是这样,则var id值为"idString" If not , value of var id is undefined . 如果不是 ,则undefined var id值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM