Phi*_*ton 754 javascript anchor jquery fragment-identifier
我有一些jQuery JavaScript代码,我想只在URL中有一个哈希(#)锚链接时运行.如何使用JavaScript检查此角色?我需要一个简单的catch-all测试来检测这样的URL:
基本上是这样的:
if (thereIsAHashInTheUrl) {
do this;
} else {
do this;
}
Run Code Online (Sandbox Code Playgroud)
如果有人能指出我正确的方向,那将非常感激.
Gar*_*eth 1355
简单:
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ton 313
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
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*eal 52
把以下内容:
<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>
Run Code Online (Sandbox Code Playgroud)
Mar*_*elm 32
如果URI不是文档的位置,则此代码段将执行您想要的操作.
var url = 'example.com/page.html#anchor',
hash = url.split('#')[1];
if (hash) {
alert(hash)
} else {
// do something else
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 19
你试过这个吗?
if (url.indexOf('#') !== -1) {
// Url contains a #
}
Run Code Online (Sandbox Code Playgroud)
(url
显然,您要检查的URL 在哪里.)
小智 15
$('#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!
});
Run Code Online (Sandbox Code Playgroud)
这将解决问题;)
您可以使用现代 JS解析 url :
\nvar my_url = new URL(\'http://www.google.sk/foo?boo=123#baz\');\n\nmy_url.hash; // outputs "#baz"\nmy_url.pathname; // outputs "/moo"\n\xe2\x80\x8bmy_url.protocol; // "http:"\n\xe2\x80\x8bmy_url.search; // outputs "?doo=123"\n
Run Code Online (Sandbox Code Playgroud)\n没有哈希值的 url 将返回空字符串。
\n以下是您可以定期检查哈希值的变化,然后调用函数来处理哈希值.
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
大多数人都知道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
}
});
Run Code Online (Sandbox Code Playgroud)