首页 > 解决方案 > 为什么我的 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();
    
  });
});`

标签: javascriptjqueryajax

解决方案


给你所有的模式一个通用的类,比如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>


推荐阅读