How can I close multiple bootstrap modals with the

2019-08-12 06:53发布

问题:

I have 2 modal popups in this code. How can i use the close button on the second popped modal to close the first and the second modal.

<button class="btn btn-default"><a href="#" data-toggle="modal" data-target="#myModal">Open First Modal</a></button>
        <div class="modal fade reply-sure" id="myModal">
          <div class="modal-dialog  modal-lg">
            <div class="modal-content">
              <div class="modal-header bg-default">
                <h4 class="modal-title">First Modal</h4>
              </div>
              <div class="modal-body">
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal2">Open Second</button>
                <button type="button" class="btn btn-info"  data-dismiss="modal">Close</button>
              </div>
            </div>
          </div>
        </div>
        <div class="modal fade reply-sure" id="myModal2">
          <div class="modal-dialog  modal-lg">
            <div class="modal-content">
              <div class="modal-header bg-default">
                <h4 class="modal-title">Second Modal</h4>
              </div>
              <div class="modal-body">
                <button type="button" class="btn btn-danger"  data-dismiss="modal">Close all</button>
              </div>
            </div>
          </div>
        </div>

回答1:

You could use $('#myModal, #myModal2').modal('hide');.

http://jsfiddle.net/L5o2pm1g/



回答2:

Bootstrap gives you access to extra to the modal function. All you have to do is select it with jQuery and then tell it what to do. See the snippet below.

function closeAll() {
  $('#myModal, #myModal2').modal('hide');
}
<button type="button" class="btn btn-danger" data-dismiss="modal" onClick="closeAll()">Close all</button>