Twitter's Bootstrap dropdowns with click event

2020-06-27 04:42发布

问题:

I'm using twitter bootstrap "dropdowns" not a "dropdown" multilevel menu with html markup.

   <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
      <li><a tabindex="-1" href="#">Action</a></li>
      <li><a tabindex="-1" href="#">Another action</a>
          <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
              <li><a tabindex="-1" href="#">Action</a></li>
              <li><a tabindex="-1" href="#">Another action</a></li>
              <li><a tabindex="-1" href="#">Something else here</a>
                  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
                     <li><a tabindex="-1" href="#">Action</a></li>
                     <li><a tabindex="-1" href="#">Another action</a></li>

                 </ul>
              </li>
              <li class="divider"></li>
              <li><a tabindex="-1" href="#">Separated link</a></li>
          </ul>
      </li>
      <li><a tabindex="-1" href="#">Something else here</a>
          <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
              <li><a tabindex="-1" href="#">Action</a></li>
              <li><a tabindex="-1" href="#">Another action</a></li>
              <li><a tabindex="-1" href="#">Something else here</a></li>
              <li class="divider"></li>
              <li><a tabindex="-1" href="#">Separated link</a></li>
          </ul>
      </li>
      <li class="divider"></li>
      <li><a tabindex="-1" href="#">Separated link</a></li>
  </ul>

I have a question. Can I add click event to show submenu?

回答1:

The submenus are showed by css. So first disable the css (hover) and add a click event to your menu item.

html example:

<div class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Show menu</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
  <li><a tabindex="-1" href="#">Action</a></li>
  <li><a tabindex="-1" href="#">Another action</a></li>
   <li class="dropdown-submenu">
    <a tabindex="-1" href="#">More options</a>
    <ul class="dropdown-menu">
        <li><a tabindex="-1" href="#">Action</a></li>
        <li><a tabindex="-1" href="#">Another action</a></li>
    </ul>
  </li>
  <li class="divider"></li>
  <li><a tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>

disable css:

.dropdown-submenu:hover > .dropdown-menu {
  display: none;
}

trigger the click by javascript:

$('.dropdown-submenu').click(function(){
  $('.dropdown-submenu > .dropdown-menu').css('display','block');
  return false;
});

Example: http://bootply.com/66088

NOTE when you have more as one submenu give each its own class