使用jQuery,有没有办法区分当前的window.location
没有散列和空散列?空散列和不散列之间的区别
这就是我所说的 “空哈希”:
http://domain.tld/#
这是 “没有哈希”:
http://domain.tld/
使用jQuery,有没有办法区分当前的window.location
没有散列和空散列?空散列和不散列之间的区别
这就是我所说的 “空哈希”:
http://domain.tld/#
这是 “没有哈希”:
http://domain.tld/
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?
你不需要jQuery的这一点。如果你有一个空的散列,那么你所要做的就是检查window.location.href
的最后一个字符。下面将返回true
如果有一个空的哈希:
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;
}
您可以用按位与运营商(&
)比较轻松的返回值。
if (getHashState() & 1); // no hash
if (getHashState() & 2); // empty hash
if (getHashState() & 4); // no empty hash
有没有办法像这样写:if(hash不为空)elseif(没有hash)else {//空hash}? – bobylapointe 2013-02-27 18:41:40
@bobylapointe:当然,虽然它没有太大的区别,因为每次只执行一个块。看我的编辑。 – 2013-02-27 19:32:55