2013-02-27 10 views

答えて

7

window.location.hashなしハッシュと空のハッシュの両方のために""を返します。空のハッシュがある場合、以下はtrueを返します。あなたには、いくつかの理由で区別を行う必要がある場合は、#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(ハッシュが空ではない){} elseif(ハッシュはありません){} else {// empty hash}? – bobylapointe

+1

@bobylapointe:もちろん、毎回1つのブロックしか実行されないので、それほど大きな違いはありません。私の編集を参照してください。 –

1

あなたは、このためのjQueryを必要としない

これは、私が "空のハッシュ" と呼んでいます。空のハッシュがある場合、最後の文字はwindow.location.hrefです。

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

あなたは、ビット単位のAND演算子(&)で簡単に返り値を比較することができます。

if (getHashState() & 1); // no hash 
if (getHashState() & 2); // empty hash 
if (getHashState() & 4); // no empty hash 
関連する問題