stopPropagation无法处理内部按钮的事件



我有一个小问题,即:

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

问题是,如果我对容器对话框(classmodal(使用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>

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!!!

最新更新