我想知道是否可以让脚本检测 URL anchor ,并加载特定于该 anchor 的内容。例如,我有这行代码:
<a href="#home"><span id="homeMenu">Home</span></a>
这行代码监听这段代码:

$("#homeMenu").click(function () {
    $("#home_content").show("slow");
    $("#accommodations_content").hide("slow");
    });

如果用户访问 http://www.myurl.com/home.html#home,我怎么能让它自动加载主页内容。这也适用于我想要实现的所有其他 anchor 。

我想要这个是因为,现在,如果用户直接访问任何 anchor ,无论哪个 anchor ,它都会始终显示主页。那么,有没有办法检测加载了哪个 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>

最佳答案

您必须在页面加载时检查哈希标签。

使用此代码:

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

if (identifier === "#home") {
     $("#home_content").show("slow");
     $("#accommodations_content").hide("slow");
}

关于jquery - 使用 Jquery 检测 anchor ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4980972/

10-13 21:51