Recupera il valore del tag hash specifico dall'URL
-
03-10-2019 - |
Domanda
In RAW JavaScript, come si potrebbe verificare che esista un tag hash specifico in un URL, quindi prendere il valore?
Esempio: http://www.example.com/index.html#hashtag1=Value1&#hashtag2=Value2
Voglio essere in grado di prendere il valore di entrambi Hashtag1 o Hashtag2.
Soluzione
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:
Controlla se è presente una "chiave hash":
HashSearch.keyExists("thekey");
Ottieni il valore per una chiave hash:
HashSearch.get('thekey');
Imposta il valore per una chiave hash e aggiorna l'hash URL:
HashSearch.set('thekey', 'hey');
Rimuovi un tasto hash dall'URL:
HashSearch.remove('thekey');
Ricarica l'hash nell'oggetto locale:
HashSearch.load();
Spingere il valore del tasto corrente impostato sull'hash URL:
HashSearch.push();
Si noti che quando una chiave non esiste e ci provi get
È tornato undefined
. Tuttavia, potrebbe esistere una chiave senza alcun valore, ad esempio #key=val&novalue
dove Novalue è una chiave senza valore. Se fate HashSearch.get("novalue")
sarebbe anche tornato undefined
. In tal caso, dovresti usare HashSearch.keyExists("novalue")
Verificare che sia davvero una chiave.
Altri suggerimenti
Lo uso e funziona bene per me. È un po 'che si aggiunge a una linea che ho raccolto da qualche parte, ci credo.
getURLHashParameter : function(name) {
return decodeURI(
(RegExp('[#|&]' + name + '=' + '(.+?)(&|$)').exec(location.hash)||[,null])[1]
);
},
window.location.hash
Dovresti darti quello che vuoi.
JQuery BBQ (Button e query) sfrutta l'evento HTML5 HashChange per consentire una storia #Hash semplice ma potente. Inoltre, JQuery BBQ fornisce un metodo .Deparam () completo, insieme alla gestione dello stato hash e ai metodi di utilità per le stringhe frammenti / query.
In breve: questa libreria consente di cambiare dinamicamente una "stringa di query" hash all'interno della tua pagina e avere l'URL corrispondenza. Inoltre, consente di estrarre dinamicamente i valori e normalizza lavorando con la "stringa di query". Infine, aggiungerà le stringhe di query nella cronologia che consente al pulsante Indietro di funzionare come una navigazione tra i precedenti valori di hash di query.
Una buona mossa per UX sarebbe quella di controllare una biblioteca come JQuery BBQ :)