jQuery / Bootstrap: Child DIV打开父模式

jQuery / Bootstrap: Child DIV opens up Parent Modal

本文关键字:模式 DIV Child Bootstrap jQuery      更新时间:2023-09-26

所以我已经嵌套了div,一个简单的版本可以像这样显示:

 $('#parent').click(function() {
  $('.parent').modal('show');
});
    
$('#child').click(function() {
  $('.parent').modal('hide'); // Added to try and hide
  $('.child').modal('show');
  $('.parent').modal('hide'); // Added to try and hide
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <div id="child">
  </div>
 </div>
  

问题是当我点击子div时,父对话框也会出现在子对话框后面

有办法解决这个问题吗?

这是因为您的孩子点击事件正在冒泡到父。使用e.stopPropogation()作为子div。这将防止您的点击事件传播到父div。

$('#parent').click(function() {
  $('.parent').modal('show');
});
    
$('#child').click(function(e) {
  e.stopPropogation();
  $('.parent').modal('hide'); // Added to try and hide
  $('.child').modal('show');
  $('.parent').modal('hide'); // Added to try and hide
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <div id="child">
  </div>
 </div>

您可以通过在如下属性中提及目标来轻松处理这种情况。

$('#parent, #child').click(function() {
   var target = $(this).data('target');
   $('.'+target).modal('show');
   // write code to hide others if necessary
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent" data-target="parent">
  <div id="child" data-target="child">
  </div>
 </div>

在显示模态之前试一下:

 $( '.modal' ).remove();
$( '.child' ).modal('show');

在使用show之前删除模态。希望这将解决您的问题