jquery - 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>
解决方案
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!!!
推荐阅读
- nestjs - 注册其接口具有强制构造函数参数的提供者
- r - Dygraph 和 Graph 未在闪亮的选项卡下呈现
- c - 在 C 中计算二进制文件的排序,仅包含 uint16_t 数字
- javascript - javascript读取docx文本的问题
- swift - SCNSceneRendererDelegate - 未调用渲染器
- android - 在 ViewPager2 中启动子片段
- php - 实现千 (k, kk) 解释器
- python - 每个国家/地区的数据框中的 Python 总和值并保留 PopData
- angular - get方法以角度返回空对象
- ffmpeg - ffmpeg 转换为 hls 时烧录的字幕不同步