Bootstrap menu collapse in ajax site. How can i cl

2019-06-03 17:34发布

问题:

my website uses Ajax and i want to close the Bootstrap's collapsed menu every time a user click click on every menu item, like this code. But this code doesn't work!! Damn!

$('.menu-item').click(function() {
$('.collapse').collapse('hide');
});

How can I fix it?

(The code of menu is a simply bootstrap 3.0.0):

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>

And the code of menu:

<div class="col-md-6 downmy">
<div class="navbar-collapse in" style="height: auto;">
<div class="menuTop"><ul id="menu-primary" class="nav nav-pills"><li id="menu-item-605" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-605"><a href="1.htm">Home</a></li>
<li id="menu-item-314" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-314"><a href="2.htm">My Posts</a></li>
<li id="menu-item-315" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-315"><a href="3.htm">Guestbook</a></li>
</ul>
</div>
</div>
</div>

回答1:

When an element with class '.collapse' collapse or become visible the '.collapse' class will be replace by the .in class. So you will have to apply your hide on the .in class too.

$('.menu-item').click(function() {
    $('.in').collapse('hide');
});

Your menu items contain an anchor, when click this a new page will open... so i don't understand your question. To prevent this add an event.preventDefault (http://api.jquery.com/event.preventDefault/) to your code:

$('.menu-item').click(function(event) {
    event.preventDefault();

$('.in').collapse('hide');
});


回答2:

The following query worked fine for me :

//The ":not('.dropdown-toggle')" is for the drop down menu (like a language menu) because 
//  I didn't want my navigation to close when clicking sub menu
$(".nav li a:not('.dropdown-toggle')").on('click',function(){
  $('.navbar-collapse.in').collapse('hide');
});

You can add it to your page or in the $(document).ready(function(){/*...*/}); method