我有一些jQuery/JavaScript代码,我想只在URL中有一个散列(#)锚链接时运行。如何使用JavaScript检查这个字符?我需要一个简单的全方位测试,可以检测到如下url:
example.com/page.html #锚 example.com/page.html # anotheranchor
基本上是这样的:
if (thereIsAHashInTheUrl) {
do this;
} else {
do this;
}
我有一些jQuery/JavaScript代码,我想只在URL中有一个散列(#)锚链接时运行。如何使用JavaScript检查这个字符?我需要一个简单的全方位测试,可以检测到如下url:
example.com/page.html #锚 example.com/page.html # anotheranchor
基本上是这样的:
if (thereIsAHashInTheUrl) {
do this;
} else {
do this;
}
当前回答
写上以下内容:
<script type="text/javascript">
if (location.href.indexOf("#") != -1) {
// Your code in here accessing the string like this
// location.href.substr(location.href.indexOf("#"))
}
</script>
其他回答
位置哈希的简单使用:
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
$('#myanchor').click(function(){
window.location.hash = "myanchor"; //set hash
return false; //disables browser anchor jump behavior
});
$(window).bind('hashchange', function () { //detect hash change
var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
//do sth here, hell yeah!
});
这将解决问题;)
大多数人都知道document.location中的URL属性。如果您只对当前页面感兴趣,那就太好了。但问题在于能否解析页面上的锚,而不是页面本身。
大多数人似乎忽略了这些URL属性也可以用于锚定元素:
// To process anchors on click
jQuery('a').click(function () {
if (this.hash) {
// Clicked anchor has a hash
} else {
// Clicked anchor does not have a hash
}
});
// To process anchors without waiting for an event
jQuery('a').each(function () {
if (this.hash) {
// Current anchor has a hash
} else {
// Current anchor does not have a hash
}
});
你可以使用现代JS解析url:
var my_url = new URL('http://www.google.sk/foo?boo=123#baz');
my_url.hash; // outputs "#baz"
my_url.pathname; // outputs "/moo"
my_url.protocol; // "http:"
my_url.search; // outputs "?doo=123"
没有哈希的url将返回空字符串。
上面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
}
(但这可能有点过头了..)