简体   繁体   中英

Having two dropdown menus in the same nav bar

As Im saying in the title of the question, I created a navigation bar with two dropdown boxes. The problem is when im trying to open one menu with hover (it worked perfectly with one dropdown box only), the second one opens the same time. This is the script I created. Any suggestion would be very happily accepted!

<script>
$(document).ready(function () {
    $(".dropdown").hover(
      function () {
    $("ul.dropdown-menu").slideDown("medium").stop(true,true);
      }, 
      function () {
    $("ul.dropdown-menu").slideUp("medium").stop(true,true);
      }  
    );
});
</script>

This is because $("ul.dropdown-menu") is a jQuery object representation of all ul elements that are of classe dropdown-menu . The same goes to $(".dropdown") .

You can use each() to solve this problem.

Iterate over a jQuery object, executing a function for each matched element.

In the callback function, use $(this) to access each jQuery object and :eq to get the nth object of $("ul.dropdown-menu") (it is 0-based so the first object is :eq(0) ). .

var a =0;
$(".dropdown").each(function(){
   var b = a;
   $(this).hover(function () {
      $("ul.dropdown-menu:eq("+b+")").slideDown("medium").stop(true,true);
   }, function() {
      $("ul.dropdown-menu:eq("+b+")").slideUp("medium").stop(true,true);
   });
   a++;
});

Provide each dropdown menu with id and call .hover() by the id like this

$("#firstDropdown").hover();
$("#secDropdown").hover();

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