简体   繁体   English

jQuery click事件在切换侧栏时仅工作一次

[英]jQuery click event works only once while toggling the sidebar

I am trying to toggle a sidebar, but it works only once. 我正在尝试切换侧边栏,但是它只能工作一次。 I think the query code is self explanatory. 我认为查询代码是不言自明的。 Though I can write the HTML code if you want. 虽然我可以根据需要编写HTML代码。

    $('.side-menu').on('click', function(){
        $('.control-sidebar').addClass('active-sidebar');
        $('.side-menu').on('click', function(){
            $('.control-sidebar').removeClass('active-sidebar');
        });
    });

A clean code solution would look somehow like this: 干净的代码解决方案看起来像这样:

$('.side-menu').on('click', function(){
    $('.control-sidebar').toggleClass('active-sidebar');
});

I think the logic is not right in your case. 我认为您的情况逻辑不正确。

if(!$('.control-sidebar').hasClass('active-sidebar')){...}

This code will run when class "control-sidebar" don't have class "active-sidebar". 当类“ control-sidebar”没有类“ active-sidebar”时,此代码将运行。

at the beginning, the case happens so you can click on .side-menu and add class "active-sidebar" to DOM. 在一开始,这种情况就发生了,因此您可以单击.side-menu并将类“ active-sidebar”添加到DOM。 this against your first logic. 这违反了您的第一个逻辑。

Moreover, why this happens twice in your code? 此外,为什么这在您的代码中发生两次?

$('.side-menu').on('click', function(){...}

Solution: Use toggle class: see this https://jsfiddle.net/BeklievParviz/rwnpk0wm/ 解决方案:使用切换类:请参阅此https://jsfiddle.net/BeklievParviz/rwnpk0wm/

$('.side-menu').on('click', function(){
    $('.control-sidebar').toggleClass('active-sidebar');
});

User This 用户此

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

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