用Jquery检测锚点?

Han*_*nna 3 html url anchor jquery

我想知道是否可以让脚本检测到URL锚点,并加载特定于该锚点的内容.例如,我有这行代码:

<a href="#home"><span id="homeMenu">Home</span></a>

这行代码监听此代码:

$("#homeMenu").click(function () {
    $("#home_content").show("slow");
    $("#accommodations_content").hide("slow");
    });
Run Code Online (Sandbox Code Playgroud)

如果用户访问http://www.myurl.com/home.html#home它自动加载主页内容,我怎么能这样做呢?这也应该适用于我想要实现的所有其他锚点.

我想要这个,因为,现在,如果用户直接访问任何锚点,没有哪个锚点,它将始终显示主页.那么,有没有办法检测加载了哪个URL,然后在其上运行脚本?

编辑

所以,目前它只装载住宿(即使在#Home上)

当前代码:

 <script type="text/javascript"> 
            $(document).ready(function() {
            document.getElementById("javascriptCheck").style.visibility = 'hidden';
            $("#menu").load("snippets/menu.html");
            $("#locationMenu").load("snippets/locationMenu.html");
            $("#home_content").load("snippets/home_content.html");
            $("#accommodations_content").load("snippets/accommodations.html");
            $("#history").load("snippets/history.html");
            $("#footer").load("snippets/footer.html");

            var hash = window.location.hash;
            if (hash = "#Home") {
                $("#home_content").show("slow");
                $("#accommodations_content").hide("slow");
            }
            if (hash = "#Accommodations") {
                $("#accommodations_content").show("slow");
                $("#home_content").hide("slow");     
            }
            } );
        </script> 
Run Code Online (Sandbox Code Playgroud)

swi*_*itz 10

您必须在页面加载时检查哈希标记.

使用此代码:

var identifier = window.location.hash; //gets everything after the hashtag i.e. #home

if (identifier === "#home") {
     $("#home_content").show("slow");
     $("#accommodations_content").hide("slow");
}
Run Code Online (Sandbox Code Playgroud)


iGE*_*GEL 5

我想,你想要这样的东西:jQuery hashchange插件.它允许您对哈希的更改作出反应,并通过AJAX加载例如其他内容 - 但您也可以执行其他操作.用户甚至可以使用浏览器的后退和前进按钮转到先前的状态.