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];
}
})();
}
Usandolo:
Controllare se una "chiave hash" è presente:
HashSearch.keyExists("thekey");
Ottenere il valore per una chiave hash:
HashSearch.get('thekey');
Impostare la valore per una chiave hash e aggiorna l'hash dell'URL:
HashSearch.set('thekey', 'hey');
rimuovere una chiave hash dall'URL:
HashSearch.remove('thekey');
Ricarica l'hash in oggetto locale:
HashSearch.load();
Spingere il valore della chiave corrente impostato per l'hash URL:
HashSearch.push();
Si noti che quando una chiave non esiste e si prova a get
, restituirà undefined
. Tuttavia, potrebbe esistere una chiave senza valore, ad esempio #key=val&novalue
, dove novalue è una chiave senza valore. Se lo fai, HashSearch.get("novalue")
restituirà anche undefined
. In tal caso, è necessario utilizzare per verificare che si tratti effettivamente di una chiave.
Ciò che è * hash tag * in url? Potresti fornire un esempio? –
@Darin Dimitrov: Suppongo che intenda l'identificatore di frammento di un URI. Ma un esempio sarebbe utile. – Gumbo
Does 'href.hash' non funziona? @Darin Dimitrov, penso che @mike significhi la parte che include e dopo il '#' nell'URL. – strager