Per coloro che sono interessati a una versione riutilizzabile della soluzione di Andy E. Ho fatto una semplice funzione per ottenere il vero stato hash, come valore bit per bit.
/**
* Checks if the location hash is given, empty or not-empty.
*
* @param {String} [href] Url to match against, if not given use the current one
* @returns {Number} An integer to compare with bitwise-operator & (AND)
*/
function getHashState(href) {
var frag = (href || window.location.href).split('#');
return frag.length == 1 ? 1 : !frag[1].length ? 2 : 4;
}
È possibile confrontare i valori di ritorno facilmente con l'AND bit a bit-operatore (&
).
if (getHashState() & 1); // no hash
if (getHashState() & 2); // empty hash
if (getHashState() & 4); // no empty hash
C'è un modo per scrivere in questo modo: se (l'hash non è vuoto) {} elseif (non c'è hash) {} else {// vuoto hash}? – bobylapointe
@bobylapointe: Certo, anche se non fa molta differenza dal momento che solo un blocco verrebbe eseguito ogni volta. Vedi la mia modifica. –