2013-02-27 46 views

回答

7

window.location.hash將返回""兩個沒有散而空哈希。如果你需要做某種原因的區別,你可以通過#分裂window.location.href

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

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

或檢查第一個現有的哈希值,按您的要求:

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

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

+0

有沒有辦法像這樣寫:if(hash不爲空)elseif(沒有hash)else {//空hash}? – bobylapointe 2013-02-27 18:41:40

+1

@bobylapointe:當然,雖然它沒有太大的區別,因爲每次只執行一個塊。看我的編輯。 – 2013-02-27 19:32:55

1

你不需要jQuery的這一點。如果你有一個空的散列,那麼你所要做的就是檢查window.location.href的最後一個字符。下面將返回true如果有一個空的哈希:

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

對於那些對Andy E的解決方案的可重用版本感興趣的人。我做了一個簡單的函數來獲取實際的散列狀態,即按位值。

/** 
* 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; 
} 

您可以用按位與運營商(&)比較輕鬆的返回值。

if (getHashState() & 1); // no hash 
if (getHashState() & 2); // empty hash 
if (getHashState() & 4); // no empty hash