为什么在单击主体之前,jQuery会打开和关闭弹出窗口?

问题描述

我弹出一个弹出窗口,以便用户可以回复消息。现在,当用户单击<a>标签时,它会打开弹出窗口,但是如果用户在身体上的任何地方碰到它,它都不会关闭。我尝试使用jquery修复此问题,但单击<a>标签后,它会保持打开状态,然后立即再次关闭弹出窗口。

我的<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();
    
  });
});`

解决方法

jQuery(document).ready(function ($) {
            function openReplyModal(id) {
                msg_id = id
                $("#reply_modal" + msg_id).addClass('model-open').fadeIn();
            }

            $('body').click(function (e) {
                $('.model-open').removeClass('open').fadeOut();
            });
        });
,

为所有模态赋予一个通用类,例如class="reply_modal"。然后,您可以使用一个通用的单击处理程序,当您单击主体时,该处理程序会将它们全部淡出。

模态立即关闭的原因是click事件从<a>冒到主体,因此它关闭了模态。我在函数中添加了event.stopPropagation(),所以它不会冒泡。

使用$(window).click()检测元素外部窗口中任何位置的点击。参见How do I detect a click outside an element?

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>