简体   繁体   English

在同一个导航栏中有两个下拉菜单

[英]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 . 这是因为$("ul.dropdown-menu")是所有属于class dropdown-menu ul元素的jQuery对象表示。 The same goes to $(".dropdown") . $(".dropdown")

You can use each() to solve this problem. 您可以使用each()解决此问题。

Iterate over a jQuery object, executing a function for each matched element. 遍历jQuery对象,为每个匹配的元素执行一个函数。

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) ). 在回调函数中,使用$(this)访问每个jQuery对象,并使用:eq获得$("ul.dropdown-menu")的第n个对象$("ul.dropdown-menu")基于0,因此第一个对象为: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 为每个下拉菜单提供ID,并通过ID调用.hover(),如下所示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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