javascript - 为什么我的 jQuery 在单击正文之前打开和关闭我的弹出窗口?
问题描述
我有一个弹出窗口,用户可以回复消息。现在,当用户单击<a>
标签时,它会打开弹出窗口,但如果他们击中身体的任何地方,它不会关闭。<a>
我尝试使用 jquery 修复此问题,但它会在单击标签后立即打开然后再次关闭弹出窗口 。
我的<a>
标签:
<a class="msg-icon2" onclick="openReplyModal(<?php echo $msg_id ; ?>)">
<i class="fas fa-reply"></i>
</a>
我的jQuery:
var msg_id;
function openReplyModal(id) {
msg_id = id
$("#reply_modal" + msg_id).fadeIn();
jQuery(document).ready(function($) {
jQuery("body").click(function() {
$("#reply_modal" + msg_id).fadeOut();
});
});
}
如何调整我的代码,以便当用户第一次单击按钮时,它将打开弹出窗口并保持打开状态,除非他单击body
?
这是我从以下答案中得到的代码:
`function openReplyModal(id, event) {
$(".modal").hide(); // close other modal
msg_id = id
$("#reply_modal" + msg_id).fadeIn();
event.preventDefault();
event.stopPropagation();
}
jQuery(document).ready(function($) {
// click on modal doesn't hide itself
$("body").on("click", ".modal", function(e) {
e.stopPropagation();
});
// clicl anywhere else hides all modals
$(window).click(function() {
$(".modal").fadeOut();
});
});`
解决方案
给你所有的模式一个通用的类,比如class="reply_modal"
. 然后,您可以拥有一个通用的单击处理程序,当您单击正文时,该处理程序会将它们全部淡出。
模态框立即关闭的原因是click
事件从主体冒泡出来<a>
,所以它关闭了模态框。我添加event.stopPropagation()
了该功能,因此它不会冒泡。
用于$(window).click()
检测元素外窗口中任意位置的点击。请参阅如何检测元素外部的点击?.
var msg_id;
function openReplyModal(id, event) {
$(".reply_modal").hide(); // close other modal
msg_id = id
$("#reply_modal" + msg_id).fadeIn();
event.preventDefault();
event.stopPropagation();
}
jQuery(document).ready(function($) {
// click on modal doesn't hide itself
$("body").on("click", ".reply_modal", function(e) {
e.stopPropagation();
});
// clicl anywhere else hides all modals
$(window).click(function() {
$(".reply_modal").fadeOut();
});
});
.reply_modal {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="msg-icon2" onclick="openReplyModal(1, event)" href="#"> <i class="fas fa-reply">open 1</i></a>
<a class="msg-icon2" onclick="openReplyModal(2, event)" href="#"> <i class="fas fa-reply">open 2</i></a>
<div id="reply_modal1" class="reply_modal">This is modal 1<br>
<input></div>
<div id="reply_modal2" class="reply_modal">This is modal 2<br>
<input></div>
推荐阅读
- reactjs - Storybook 是否支持异步导入?
- javascript - 在 EJS 模板中,为什么 Javascript 承诺在写在 1 行时可以工作,但在 3 行时会失败?
- java - 如何在同一行中同时打印 bool 和 double?
- javascript - 如何在页面上只获取我感兴趣的 HTML?
- angular - 在 Angular 8 组件中切换 MatSlideToggle
- javascript - 在链接构造函数中使用“this”
- python - Pandas 滚动函数加值
- windows - 将 Docker 容器中的文件夹与本地计算机上的文件夹连接 - 权限被拒绝
- python - 使用相邻单元格中的名称保存 excel 中的图像
- c++ - C(++) 短减 short = int?