使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:19:48  来源:igfitidea点击:

Get #anchor for URL using jQuery ?

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-productsis hidden and #red-informationis visible. Sometimes I want #red-productsto be visible and #red-informationhidden, 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-productsand 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-productsand 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-informationas you have now.

这将首先隐藏两者,然后显示 hasd ( #red-hashhere),或默认显示#red-information为您现在所拥有的。