jQueryを使用して、現在のwindow.location
でハッシュと空のハッシュを区別する方法はありますか?空のハッシュとハッシュなしの違い
http://domain.tld/#
そして、これが "NOハッシュ" ではありません:
http://domain.tld/
jQueryを使用して、現在のwindow.location
でハッシュと空のハッシュを区別する方法はありますか?空のハッシュとハッシュなしの違い
http://domain.tld/#
そして、これが "NOハッシュ" ではありません:
http://domain.tld/
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?
あなたは、このためのjQueryを必要としない
これは、私が "空のハッシュ" と呼んでいます。空のハッシュがある場合、最後の文字はwindow.location.href
です。
window.location.href.lastIndexOf('#') === window.location.href.length - 1
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
if(ハッシュが空ではない){} elseif(ハッシュはありません){} else {// empty hash}? – bobylapointe
@bobylapointe:もちろん、毎回1つのブロックしか実行されないので、それほど大きな違いはありません。私の編集を参照してください。 –