使用 jQuery 获取 URL 的 #anchor ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4483044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get #anchor for URL using jQuery ?
提问by Adam Ramadhan
jQuery(document).ready(function(){
$("#red-products").hide();
$("#content-info").click(function(event){
$("#red-products").hide();
$("#red-information").show();
});
$("#content-product").click(function(event){
$("#red-information").hide();
$("#red-products").show();
});
$("#more").click(function(event){
load(this.href);
return false;
});
});
As you can see, by default #red-products
is hidden and #red-information
is visible. Sometimes I want #red-products
to be visible and #red-information
hidden, meaning something like
如您所见,默认情况下#red-products
是隐藏且#red-information
可见的。有时我想#red-products
变得可见和#red-information
隐藏,意思是
http://localhost/networks2/profile.php?id=1&offset=1#products
http://localhost/networks2/profile.php?id=1&offset=1#products
to show #red-products
and hide #red-information
. And
显示#red-products
和隐藏#red-information
。和
http://localhost/networks2/profile.php?id=1&offset=1#information
http://localhost/networks2/profile.php?id=1&offset=1#information
to hide #red-products
and show #red-information
.
隐藏#red-products
和显示#red-information
。
How can I read anchor from URL using jQuery, and hide/show appropriate sections?
如何使用 jQuery 从 URL 读取锚点,并隐藏/显示适当的部分?
回答by Nick Craver
You can change the initial hide to be based on window.location.hash
, by replacing this:
您可以window.location.hash
通过替换以下内容将初始隐藏更改为基于:
$("#red-products").hide();
With this:
有了这个:
$("#red-products, #red-information").hide();
$("#red-" + (window.location.hash.replace("#", "") || "information")).show();
This will hide both initially, then show the hasd (#red-hashhere
), or default to showing #red-information
as you have now.
这将首先隐藏两者,然后显示 hasd ( #red-hashhere
),或默认显示#red-information
为您现在所拥有的。