2013-02-27 12 views
5

Utilizzando jQuery, esiste un modo per distinguere tra hash e un hash vuoto sull'attuale window.location?Differenza tra hash vuoto e no hash

Questo è quello che io chiamo un "hash vuoto":

http://domain.tld/# 

E questo è "no hash":

http://domain.tld/ 

risposta

7

window.location.hash tornerà "" sia senza hash e hash vuota. Se è necessario fare una distinzione, per qualche motivo, si potrebbe dividere window.location.href da #:

var frag = window.location.href.split("#"); 

if (frag.length == 1) { 
    // No hash 
} 
else if (!frag[1].length) { 
    // Empty hash 
} 
else { 
    // Non-empty hash 
} 

o il controllo di hash esistente prima, secondo la vostra richiesta:

if (window.location.hash) { 
    // Non-empty hash 
} 
else if (window.location.href.split("#").length == 1) { 
    // No hash 
} 
else { 
    // Empty hash 
} 

Vedi anche: How to remove the hash from window.location with JavaScript without page refresh?

+0

C'è un modo per scrivere in questo modo: se (l'hash non è vuoto) {} elseif (non c'è hash) {} else {// vuoto hash}? – bobylapointe

+1

@bobylapointe: Certo, anche se non fa molta differenza dal momento che solo un blocco verrebbe eseguito ogni volta. Vedi la mia modifica. –

1

Non avete bisogno di jQuery per questo. Se hai un hash vuoto, allora tutto ciò che devi fare è controllare l'ultimo carattere di window.location.href. Di seguito tornerà true se c'è un hash vuoto:

window.location.href.lastIndexOf('#') === window.location.href.length - 1 
0

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