Jquery - 有条件的下拉菜单不会保持打开状态

Jquery - Conditional dropdown does not stay open

我正在尝试构建下拉菜单。

  1. 点击后打开。
  2. 单击子菜单项时保持打开状态。
  3. 当我点击屏幕上的其他地方时关闭。

  4. 可以。

  5. 不行。
  6. 可以。

我找不到我使用的逻辑错误,感谢任何帮助!

谢谢!

$

    // Dropdown menu icon animation up/down toggle.

$('.dropbtn').on('click', function() {
  $('#myDropdown').slideToggle();
  $(this).find('i').toggleClass('fa-sort-up fa-sort-down')
});


// Dropdown menu up/down toggle.


$(document).mouseup(function(e) {
  var container = $(".dropdownmenu");
        if (!container.is(e.target) 
      && container.has(e.target).length === 0


       ) 

  {
    $("#myDropdown").slideUp();
    $('.dropbtn i').addClass('fa-sort-up').removeClass('fa-sort-down')
  }
});

HTML

<div class="dropdown">
                  <div class="dropdownmenu">
                    <button class="dropbtn main">Diet or Allergen Filter <i class="fa fa-sort-up" style="font-size:24px; line-height:0px; margin-left: 5px;"></i></button></div>
                    <div id="myDropdown" class="dropdown-content">
                        <a id="veganDiet" class="dropbtn"><img src="http://www.padthai.decorolux.com/wp-content/uploads/2017/11/vegan2-1.png"  style="width:40px; display:inline; height:20px; vertical-align:middle;"> Vegan</a>
                        <a id="vegetarianDietButton" class="dropbtn"><img src="http://www.padthai.decorolux.com/wp-content/uploads/2017/11/vegetarian-1.png" style="width:40px; height:20px; display:inline; vertical-align:middle;"> Vegetarian</a>
                        <a id="noAddesSugarButton" class="dropbtn"><img src="http://www.padthai.decorolux.com/wp-content/uploads/2017/11/sugarfree-1.png" style="width:40px; height:20px; display:inline; vertical-align:middle;"> No Added Sugar</a>
                    </div>
                </div>

此外,这是实时代码笔:

https://codepen.io/Pbalazs89/full/ZxQbqY

在这里,试试这个

$(document).mouseup(function(e) {
    //if you are clicking on the a tags inside #myDropdown stop 
    //propagation of the event up the DOM (prevent it from getting to 'document')
    if($(e.target).is('#myDropdown a')){
        e.stopPropagation();
    }else{
        $("#myDropdown").slideUp();
        $('.dropbtn i').addClass('fa-sort-up').removeClass('fa-sort-down')
    }
});

事件传播是从内到外进行的,当您单击一个元素时,您会触发它的事件,然后是其父级的事件,依此类推; e.stopPropagation() 阻止了这种情况的发生,因此 mouseup 事件只会到达 document 如果你没有点击你的 #myDropdown a.

试试看和 LMK