jQuery导航控件

Posted

技术标签:

【中文标题】jQuery导航控件【英文标题】:jQuery navigation control 【发布时间】:2014-01-02 20:19:36 【问题描述】:

我想用 jquery 显示和隐藏我网站的内容。如果我单击导航中的链接,内容应显示带有特殊 ID 的 <section>。 这是我的代码:

导航:

$(document).ready(function()
  $("a").click(function()
    $("section#home").css("display":"none");
    $("section#order").css("display":"none");
    $("section#projects").css("display":"none");
    $("section#contact").css("display":"none");
    $("section#about").css("display":"none");

    if ($(this[href="home"]))
        $("section#home").css("display":"block");
     else if ($(this[href="order"]))
        $("section#order").css("display":"block");
     else if ($(this[href="projects"]))
        $("section#projects").css("display":"block");
     else if ($(this[href="contact"]))
        $("section#contact").css("display":"block");
     else if ($(this[href="about"]))
        $("section#about").css("display":"block");
    
  );
);

html 文件:

<section id="content">
                <section id="home">
                    <h1>home</h1>
                </section>
                <section id="order">
                    <h1>order</h1>
                </section>
                <section id="projects">
                    <h1>projects</h1>
                </section>
                <section id="contact">
                    <h1>contact</h1>
                </section>
                <section id="about">
                    <h1>about</h1>
                </section>
</section>

它在每个导航链接上都显示相同的页面(主页)。怎么了? 你可以自己看Homepage

【问题讨论】:

【参考方案1】:

你的if条件语法错误,应该是$(this).is('[href="home"]')

$(document).ready(function () 
    $("a").click(function (e) 
        e.preventDefault();

        //hide all sections under #content
        $('#content > section').hide();

        //show the elemet with the given href as the id
        $('#' + $(this).attr('href')).show();

    );
);

【讨论】:

【参考方案2】:

您必须hide id 为content 的部分内的所有children 部分。然后只需从单击的锚标记中获取href 属性。并显示section,其 id 与单击的锚标记相同。

试试,

$(document).ready(function()
  $("a").click(function(e)
    e.preventDefault();       
    $('#content').children('section').hide();    
    $('#' + $(this).attr('href')).show();
  );
);

【讨论】:

不工作..查看链接,您的代码已上传,但是...不工作;( @Tekkzz 从选择器中删除连接的#。查看我更新的代码。 e.preventDefault() 是做什么的? @Tekkzz 您刚刚更改了标记,删除了 href 中的 #。现在,当您单击它时,您的页面将被重新加载。所以为了防止它你应该使用e.preventDefault()。从技术上讲,它会阻止默认行为。 啊,谢谢你的信息

以上是关于jQuery导航控件的主要内容,如果未能解决你的问题,请参考以下文章

jQuery Mobile 选项卡导航延迟

JQuery jCarousel - 禁用外部控件

多个 jQuery Cycle 寻呼机导航

向导导航栏控件----------WinForm控件开发系列

openlayers入门开发系列之地图导航控件篇

如何在导航控件片段中关闭导航 DrawerLayout onBackPressed