我有一些jQuery/JavaScript代码,我希望只在URL中存在散列符号(#
)时运行它。如何使用JavaScript检查此字符?我需要一个简单的测试,可以检测到这样的URL:
example.com/page.html#anchor
example.com/page.html#anotheranchor
基本上是这样:
if (thereIsAHashInTheUrl) {
do this;
} else {
do this;
}
我有一些jQuery/JavaScript代码,我希望只在URL中存在散列符号(#
)时运行它。如何使用JavaScript检查此字符?我需要一个简单的测试,可以检测到这样的URL:
example.com/page.html#anchor
example.com/page.html#anotheranchor
基本上是这样:
if (thereIsAHashInTheUrl) {
do this;
} else {
do this;
}
使用位置哈希值的简单方法:
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
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
}
请放置以下内容:
<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>
var url = 'example.com/page.html#anchor',
hash = url.split('#')[1];
if (hash) {
alert(hash)
} else {
// do something else
}
你试过这个吗?
if (url.indexOf('#') !== -1) {
// Url contains a #
}
(其中url
是你想要检查的URL,显然。)
$('#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!
});
这会解决问题的;)
window.location.hash
将返回哈希标识符
...或者有一个jQuery选择器:
$('a[href^="#"]')
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"
以下是您可以定期检查哈希值更改并调用函数处理哈希值的方法。
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);
}
.search
方法可用于<a>
元素而非.query
。示例 jQuery 代码如下:$("<a/>").attr({ "href": "http://www.somewhere.com/a/b/c.html?qs=1#fragmenttest" })[0]
。.hash => "#fragmenttest"
,.search
=?qs=1
。接下来,请查看 querystring extraction question 中的问题以获取除字符串以外的其他内容。 - patridgewindow.location.hash
为空。 如果您正在寻找哈希,则没有问题,但是如果您想检查当前URL是否包含“#”,则不行。 - fela