简体   繁体   中英

jQuery / Bootstrap: Child DIV opens up Parent Modal

So I have nested DIVs and a simple version can be shown like this:

  $('#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> 

The thing is when I click on the child div, the parent dialog also shows up behind the child dialog.

Any way to get around this?

It is happending because your child click event is bubbling up to the parent. Use e.stopPropogation() for the child div. This will prevent your click event from propogating to the parent.

 $('#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> 

You can deal with such cases easily by mentioning the target in an attribute like below.

$('#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>

Try this before showing the modal:

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

Remove the modal before using show. Hope this will fix your issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM