我有一些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;
}
当前回答
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
其他回答
你试过这个吗?
if (url.indexOf('#') !== -1) {
// Url contains a #
}
(url显然是你要检查的url。)
如果URI不是文档的位置,这个代码段将按照您的要求执行。
var url = 'example.com/page.html#anchor',
hash = url.split('#')[1];
if (hash) {
alert(hash)
} else {
// do something else
}
写上以下内容:
<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>
window.location.hash
将返回哈希标识符
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
}