首页 > 解决方案 > 单击时选择一个下拉菜单,而不是多个

问题描述

我有多个带有砖石的卡片,并且在单击图标时添加了一个下拉菜单。当我点击图标时,每张卡片都会显示下拉菜单,或者我只想要我点击的那个。

HTML:

<div class="dropdown">
<i class="fas fa-share-alt-square social-menu"></i>
<div class="dropdown-content">
    <a href="https://www.facebook.com"></i>Facebook</a>
    <a href="https://www.facebook.com"></i>Facebook</a>
</div>

JS:

$('.social-menu').click(function() {
    $('.dropdown-content').toggleClass('show');
  });
  $(document).click(function(event) {
    if (!$(event.target).closest('.social-menu').length) {
      if ($('.dropdown-content').is(":visible")) {
        $('.dropdown-content').toggleClass('show');
      }
    }
  });

标签: javascriptphp

解决方案


你真的不需要 2click处理程序来做到这一点。

您唯一需要记住的是,您必须show真正dropdown-content接近social-menu被点击。考虑到您的HTML结构,您可以这样做:

$('.social-menu').click(function() {
    var parentDiv = $(this).closest(".dropdown"); //find the parent div holding <i> as well as dropdown-content
    parentDiv.find('.dropdown-content').toggleClass('show'); //target the exact dropdown-content
});

推荐阅读