Issue with accordion menu closing when clicking on child list items

时间:2017-04-10 01:09:25

标签: jquery html css css3

I am trying to create an accordion menu so that when you click on the parent li item, the child list items will expand out.

The issue that I am running into with my JS is that since the child lists are located beneath the parent li item, when you click on the child, it is closing the elements.

You can see my code here: https://jsfiddle.net/rdjv6z4a/

Ultimately, I only want one of the items open at any given time, but I don't want the parent item to close when you click on the child list items.

Does anyone see where I have made my mistake(s)?

2 个答案:

答案 0 :(得分:0)

Add stopPropagation to the sub ul or li

$(document).on("click", "#filter-options li.options ul", function(e) {
  e.stopPropagation();
});

The issue is because of event bubbling, the click on the sub ul bubbles up the DOM to the document unless a stopPropagation is hit and on it's way up it triggers the click on the parent .options and toggles the menu.

答案 1 :(得分:0)

There are many ways for you to check whether the event is triggered from the parent item not from the children. One quick way to do this in your case is to change the selector of the click event to #filter-options li.options > span:

    $(document).on("click", "#filter-options li.options > span", function() {
      var $option = $(this).parent(); // this will be the parent item
        $("#filter-options li.options ul").slideUp();
        $("#filter-options li.options i").removeClass("fa-caret-down").addClass("fa-caret-up");
        if ($option.hasClass("active")) {
          $option.find("i").removeClass("fa-caret-down").addClass("fa-caret-up");
          $option.removeClass("active");
          $option.find("ul").slideUp();
        } else {
          $option.find("i").removeClass("fa-caret-up").addClass("fa-caret-down");
          $option.addClass("active");
          $option.find("ul").slideDown();
        }
        return false;
      });