我有一些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;
}
当前回答
有时您会得到完整的查询字符串,例如“#anchorlink?”firstname =马克”
这是我获取哈希值的脚本:
var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);
returns -> #anchorlink
其他回答
上面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
}
(但这可能有点过头了..)
if(window.location.hash) {
var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
alert (hash);
// hash found
} else {
// No hash found
}
有时您会得到完整的查询字符串,例如“#anchorlink?”firstname =马克”
这是我获取哈希值的脚本:
var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);
returns -> #anchorlink
function getHash() {
if (window.location.hash) {
var hash = window.location.hash.substring(1);
if (hash.length === 0) {
return false;
} else {
return hash;
}
} else {
return false;
}
}
我注意到所有这些答案都主要检查window.location.hash,这使得编写测试变得困难。
const hasHash = string => string.includes('#')
你也可以像这样从url中删除散列:
const removeHash = string => {
const [url] = string.split('#')
return url
}
最后你可以把逻辑组合在一起:
if(hasHash(url)) {
url = removeHash(url)
}