首页 > 解决方案 > stopPropagation 对内部按钮的事件不起作用

问题描述

我有一个小问题,即:

我写了一个脚本,当它点击覆盖对话框时会关闭它。此外,对话框包含一个关闭按钮,通过.html() 函数动态加载。

问题是,如果我对容器对话框(类模式)使用 e.stopPropagation (),则 .close-modal 按钮将停止工作。

我怎样才能解决这个问题?

$(".modal").html('<a class="close-modal" href="#">close</a> <a href="#">do any stuff</a>');

$(".modal-overlay").on("click", function(e) {

  $(this).fadeOut("slow");

});

$(document).on("click", ".close-modal", function(e) {

  $(".modal-overlay").fadeOut("slow");

});

$(".modal").on("click", function(e) {

  e.stopPropagation();

});
.modal-overlay {
  width: 100%;
  height: 100%;
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
}

.modal {
  background: #fff;
  position: absolute;
  width: 50%;
  left: 50%;
  margin-left: -25%;
  top: 50%;
  transform: translateY(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-overlay">
  <div class="modal">
  </div>
</div>

标签: jquerystoppropagation

解决方案


Event stop propagation will stop the subsequent events, there by in your case .modal click event will fire first and stop propagation will stop the invocation of .close-modal and .modal-overlay events. 

    To handle this, you can use the below code.

        $(".modal").on("click", function(e) {
        if ($(e.target).is($(this)))
          e.stopPropagation();
        });

    Hope it helps! Happy coding!!!

推荐阅读