jquery - 使用 Jquery 检测 anchor ?

标签 jquery html url anchor

我想知道是否可以让脚本检测 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,然后在该 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/

相关文章:

javascript - JS 问候语不起作用

html - 减少 svg 图像的厚度(箭头)

url - Azure 网站 - 使用 web.config 进行 URL 重写不起作用

Swift - 从服务器上的特定文件夹/远程 URL 中获取所有文件

regex - 从 &lt;script&gt; 中提取的数据的 Url 正则表达式

javascript - Jquery resize() api 混淆

javascript - 将 Javascript 序列化转换为 Javascript 对象

javascript - 从数据库插入下拉列表到wordpress页面($.post没有功能)

css - 如何在 Position 中正确设置 Images

php - wordpress functions.php 没有为 CSS 显示任何内容