简体   繁体   English

用户单击时,jQuery动态添加和删除类

[英]jQuery adding and removing classes dynamically when the user clicked

I've a problem with the following code. 我的以下代码有问题。 I've two tabs in my navigation Tab-1 & Tab-2 , when the user click on any tab, then I want to add the active class to it and at the same time I want to remove the active class from previously active tab. 我在导航选项卡1和选项卡2中有两个选项 ,当用户单击任何选项卡时,我想向其添加活动类,同时我想从以前的活动选项卡中删除活动类。 Also the tab which is currently active should display its content and have to hide the remaining content. 此外,当前处于活动状态的选项卡应显示其内容,并且必须隐藏其余内容。 It means when the user clicked on any tab it should display only its content and the other contents should be hidden. 这意味着,当用户单击任何选项卡时,它应仅显示其内容,而其他内容应被隐藏。 Please help me thank you. 请帮我谢谢。

<style>
    .wrapper .tabs {
        display: none;
    }
    .wrapper .tabs.active {
        display: block;
    }
</style>

<div class="wrapper">

    <!-- Navigation -->
    <ul class="nav">
        <li class="active"><a href="#tab-1">Tab-1</a></li>
        <li><a href="#tab-2">Tab-2</a></li>
    </ul>

    <!-- Panel-1 -->
    <div id="tab-1" class="tabs active">
        <p>Tab-1 Content</p>
    </div>

    <!-- Panel-2 -->
    <div id="tab-2" class="tabs">
        <p>Tab-2 Content</p>
    </div>

</div>

<!-- Script -->
<script>
    $(document).ready(function () {
        $('.nav li').click(function() {
            $('.nav li.active').removeClass('active');
            $(this).addClass('active');
        });

        // To display content for active class only
        $('.nav li').click(function() {
            $('.wrapper .tabs.active').removeClass('active');
            $(this).addClass('active');
        });
    });
</script>

You can use .eq() , .index() at click event attached to selector "a[href^='#tab-']" which selects element where href begins with #tab- , create variable referencing elements where id begins with tab- , call event.preventDefault() within click function to prevent navigation to document fragment, .hide() , .show() 您可以在附加到选择器"a[href^='#tab-']" click事件上使用.eq() .index() ,该选择器选择href#tab-开头的元素,创建变量引用以id开头的元素tab- ,调用event.preventDefault()click功能,防止导航到文档片段, .hide() .show()

  $(document).ready(function() { var a = $("a[href^='#tab-']"); var tabs = $("[id^=tab]"); a.click(function(e) { e.preventDefault(); tabs.hide().eq(a.index(this)).show() }) }) 
 #tab-1 { display: block; } [id^="tab"]:not(#tab-1) { display: none; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"> </script> <div class="wrapper"> <!-- Navigation --> <ul class="nav"> <li> <a href="#tab-1">Tab-1</a> </li> <li> <a href="#tab-2">Tab-2</a> </li> </ul> <!-- Panel-1 --> <div id="tab-1" class="tabs active"> <p>Tab-1 Content</p> </div> <!-- Panel-2 --> <div id="tab-2" class="tabs"> <p>Tab-2 Content</p> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM