简体   繁体   中英

How to improve the code JS (Jquery)? A simple dropdown

How to edit code, to close the dropdown menu on second click. In page I have many dropdowns.

 $('.dropdown').on('click', function() { var active = 'active'; $(document).on('click', function() { $('.dropdown').removeClass(active); }); $('.dropdown').removeClass(active); $(this).toggleClass(active); return false; });
 .dropdown { margin: 50px; width: 30px; height: 30px; position: relative; display: block; background: #333; cursor: pointer; } .dropdown ul { display: none; width: 100px; position: relative; bottom: -120%; left: -100%; } .dropdown.active ul { display: block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="dropdown"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div> <div class="dropdown"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div>

As shown in example, just want to add to the menu from closing up when you click on the square.

Just a simple line will suffice

$('.dropdown').on('click',function() {
  $(this).find("ul").toggle();
});

Try this,

$(document).on('click', function(e){
    if($(e.target).parents('div.dropdown').length) {
        return false;
    }        
    $('.dropdown').toggleClass('active');
    return false;        
});

Live Demo

Updated for multiple dropdowns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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