改进JavaScript - jQuery代码为活动菜单和显示/隐藏div [英] Improve JavaScript - jQuery code for active menu and show/hide div

查看:102
本文介绍了改进JavaScript - jQuery代码为活动菜单和显示/隐藏div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何改进这段代码?
在导航中有3个菜单按钮。第一个默认是活动的。在点击时,其他按钮分配有活动类别。

I am wondering how can this code be improved? I have 3 menu buttons in navigation. The first one is active by default. On click, other buttons are assigned with class active.

<div class="mobile-nav">
    <ul>
        <li><input class="mobile-nav-tab active" id="search-tab" type="button"/></li>
        <li><input class="mobile-nav-tab" id="menu-tab" type="button"/></li>
        <li><input class="mobile-nav-tab" id="members-tab" type="button"/></li>
    </ul>
</div>

这些按钮将显示一个特定的div并隐藏其他按钮。

each of these buttons will show a certain div and hide the others.

<div class="mobile-nav-content">
    <div id="search">

    </div>
    <div style="display:none" id="menu">
        <br>menu
        <br>menu
    </div>
    <div style="display:none" id="members">
        <br>members
        <br>members
    </div>
</div>

我有这个代码,运行正常。

I have this code and it is working fine.

$(document).ready(function(){
    $('.mobile-nav-tab').click(function(){
        $('.mobile-nav-tab').removeClass('active');
        $(this).addClass('active');
        if ($('#search-tab').hasClass('active')){
            $('#search').slideDown();
        }
        else{
            $('#search').hide();
        }
        if ($('#menu-tab').hasClass('active')){
            $('#menu').slideDown();
        }
        else{
            $('#menu').hide();
        }
        if ($('#members-tab').hasClass('active')){
            $('#members').slideDown();
        }
        else{
            $('#members').hide();
        }
    });
}); 

我发现我可以使用Ternary运算符来缩写if-else部分。
但我不知道有没有其他方法来改进它,并缩短?

I found out that i can shorthand if-else parts with Ternary operator. But i wonder is there any other way to improve it and make it shorter?

推荐答案

大大:

$(".mobile-nav-tab").click(function() {
    var parts = this.id.split("-");
    $(".mobile-nav-content").children().slideUp();

    $('.mobile-nav-tab').removeClass('active');
    $(this).addClass("active");
    $("#" + parts[0]).slideDown();
});

这篇关于改进JavaScript - jQuery代码为活动菜单和显示/隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆