MAO-EYE 2018-05-16 11:29 采纳率: 100%
浏览 16

Ajax无法停止传播

I read data using xhttpRequest from xml files to build a nested list. All data goes in <li></li> are dynamic loaded from xml files. the ajax and html structure is like below:

$("#category" ).on('click','.toggle',function(e){
    e.stopPropagation();
    if(!$(this).hasClass("opened")){
        $(this).children("i").removeClass("fa-plus-square");
        $(this).children("i").addClass("fa-minus-square");
        $(this).children('.sub').show();
        $(this).addClass("opened");
    }else{
        $(this).children("i").removeClass("fa-minus-square");
        $(this).children("i").addClass("fa-plus-square");
        $(this).children('.sub').hide();
        $(this).removeClass("opened");    
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="category">
  <li class="toggle">
    <i class="fa"></i><a>category here</a>
    <ul class="sub">
      <li>product here</li>
    </ul>
  </li>
</ul>

The main menu is categories. The submenu is products in the category.
I want the submenu opens when I click on the main menu, and closes When I click on the main menu again. But what I got is, the submenu closes when I click on a node in the submenu, which should remain open when I do some actions on submenu rather than main menu.

Could any of you correct the bug for me? Thanks.

</div>
  • 写回答

1条回答 默认 最新

  • 关注

    The problem is, that the event has already bubbled up before you catch it. Here's my small solution for that.

    $("#category").on('click', '.toggle', function(e) {
      e.stopPropagation();
      if (e.target.classList.contains("product")) {
        // do nothing
      } else {
        if (!$(this).hasClass("opened")) {
          $(this).children("i").removeClass("fa-plus-square");
          $(this).children("i").addClass("fa-minus-square");
          $(this).children('.sub').show();
          $(this).addClass("opened");
        } else {
          $(this).children("i").removeClass("fa-minus-square");
          $(this).children("i").addClass("fa-plus-square");
          $(this).children('.sub').hide();
          $(this).removeClass("opened");
        }
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul id="category">
      <li class="toggle">
        <i class="fa"></i><a>category here</a>
        <ul class="sub">
          <li class="product">product here</li>
        </ul>
      </li>
    </ul>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向