我有一些jQuery/JavaScript代码,我想只在URL中有一个散列(#)锚链接时运行。如何使用JavaScript检查这个字符?我需要一个简单的全方位测试,可以检测到如下url:

example.com/page.html #锚 example.com/page.html # anotheranchor

基本上是这样的:

if (thereIsAHashInTheUrl) {
    do this;
} else {
    do this;
}

当前回答

把它放在这里,作为从任意类似uri的字符串中抽象位置属性的方法。虽然窗口。如果location instanceof location为true,则任何调用location的尝试都会告诉你它是一个非法构造函数。你仍然可以通过将你的字符串设置为DOM锚元素的href属性来获得诸如散列,查询,协议等,然后它将与window.location共享所有的地址属性。

最简单的方法是:

var a = document.createElement('a');
a.href = string;

string.hash;

为了方便起见,我写了一个小库,利用它来替换本机Location构造函数,使用一个将接受字符串并产生窗口的构造函数。位置类对象:Location.js

其他回答

下面是定期检查哈希值变化的方法,然后调用一个函数来处理哈希值。

var hash = false; 
checkHash();

function checkHash(){ 
    if(window.location.hash != hash) { 
        hash = window.location.hash; 
        processHash(hash); 
    } t=setTimeout("checkHash()",400); 
}

function processHash(hash){
    alert(hash);
}

上面Partridge和Gareths的评论很棒。他们应该得到一个单独的答案。 显然,hash和search属性在任何html Link对象上都是可用的:

<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz
</script>

Or

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

如果你需要在一个常规的字符串变量上使用jQuery, 这应该可以工作:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(但这可能有点过头了..)

有时您会得到完整的查询字符串,例如“#anchorlink?”firstname =马克”

这是我获取哈希值的脚本:

var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);

returns -> #anchorlink

通常是点击跳转,而不是位置更改, 所以在点击之后设置timeout是一个好主意 获取更新的window.location.hash

$(".nav").click(function(){
    setTimeout(function(){
        updatedHash = location.hash
    },100);
});

或者你可以收听位置:

window.onhashchange = function(evt){
   updatedHash = "#" + evt.newURL.split("#")[1]
};

我写了一个jQuery插件 你想做什么。

这是一个简单的锚路由器。

var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);