简体   繁体   中英

JS dropdown menu doesn't work

I have some js code, that has to open my menu on hover. But it doesn't react on mouseover/out. Where am i mistaken?

jQuery(document).ready(function() {
        jQuery('#user-menu').bind('mouseover', openSubMenu);
        jQuery('#user-menu').bind('mouseout', closeSubMenu);

        function openSubMenu() {
            jQuery(this).find('.dropdown-menu').css('display', 'block');    
        };

        function closeSubMenu() {
            jQuery(this).find('.dropdown-menu').css('display', 'none'); 
        };

    });

And some html code here

<div id="user-menu" class="pull-right btn-group"><a class="btn btn-success dropdown-toggle" data-toggle="dropdown" href="#">User menu
  <span class="caret"></span>
    </a>
    <ul class="dropdown-menu" id="user_dropdown_menu"><li class="menu-2 first"><a href="/courses/user">My account</a></li>
<li class="menu-15 last"><a href="/courses/user/logout">Log out</a></li>
</ul>
  </div>

I would suggest using jQuery's hover instead:

$(document).ready(function() {
    $('#user-menu').hover(function () {
        $(this).find('.dropdown-menu').toggle();
    });
});

Notes:

  • passing one function to hover will fire it for both mouseover and mouseout
  • toggle will show or hide depending on the element's current state

try this:

jQuery(document).ready(function() {
  function openSubMenu() {
         jQuery(this).find('.dropdown-menu').css('display', 'block');
  };
  function closeSubMenu() {
         jQuery(this).find('.dropdown-menu').css('display', 'none');
  };

  jQuery('#user-menu').bind('mouseover', openSubMenu);
  jQuery('#user-menu').bind('mouseout', closeSubMenu);
}); 

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