从url中检索特定哈希标记的值 [英] Retrieve specific hash tag's value from url
问题描述
在原始Javascript中,如何检查网址中是否存在特定的哈希标记,然后获取值?
In raw Javascript, how would one go about checking that a specific hash tag exists in a url, then grab the value?
示例: http://www.example.com/index.html#hashtag1=value1&#hashtag2=值2
我希望能够获取 hashtag1 或 hashtag2 的值。
I want to be able to grab the value of either hashtag1 or hashtag2.
推荐答案
var HashSearch = new function () {
var params;
this.set = function (key, value) {
params[key] = value;
this.push();
};
this.remove = function (key, value) {
delete params[key];
this.push();
};
this.get = function (key, value) {
return params[key];
};
this.keyExists = function (key) {
return params.hasOwnProperty(key);
};
this.push= function () {
var hashBuilder = [], key, value;
for(key in params) if (params.hasOwnProperty(key)) {
key = escape(key), value = escape(params[key]); // escape(undefined) == "undefined"
hashBuilder.push(key + ( (value !== "undefined") ? '=' + value : "" ));
}
window.location.hash = hashBuilder.join("&");
};
(this.load = function () {
params = {}
var hashStr = window.location.hash, hashArray, keyVal
hashStr = hashStr.substring(1, hashStr.length);
hashArray = hashStr.split('&');
for(var i = 0; i < hashArray.length; i++) {
keyVal = hashArray[i].split('=');
params[unescape(keyVal[0])] = (typeof keyVal[1] != "undefined") ? unescape(keyVal[1]) : keyVal[1];
}
})();
}
使用:
检查是否存在哈希键:
HashSearch.keyExists("thekey");
获取散列键的值:
HashSearch.get('thekey');
设置散列键的值,并更新URL散列:
Set the value for a hash key, and update the URL hash:
HashSearch.set('thekey', 'hey');
从网址中删除哈希密钥:
Remove a hash key from the URL:
HashSearch.remove('thekey');
将哈希重新加载到本地对象中:
Reload the hash into the local object:
HashSearch.load();
将当前键值设置为URL哈希:
Push the current key value set to the URL hash:
HashSearch.push();
请注意,当某个密钥不存在且您尝试 get
它,它将返回 undefined
。但是,密钥可能存在且没有值 - 例如 #key = val& novalue
其中novalue是没有值的密钥。如果您执行 HashSearch.get(novalue)
,它还将返回 undefined
。在这种情况下,您应该使用 HashSearch.keyExists(novalue)
来验证它确实是一个密钥。
Note that when a key does not exist and you try to get
it, it will returned undefined
. However, a key could exist with no value -- for example #key=val&novalue
where novalue is a key with no value. If you do HashSearch.get("novalue")
it would also return undefined
. In which case, you should use HashSearch.keyExists("novalue")
to verify that it is indeed a key.
这篇关于从url中检索特定哈希标记的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!