打开bootstrap模式时的事件传播

时间:2018-01-30 16:52:05

标签: javascript jquery twitter-bootstrap

我在div中有一个bootstrap模态按钮。我想要它,以便当我点击按钮时模态打开但它忽略了外部div的任何编程。我可以使用event.stopPropagation();但模态不会打开。任何人都可以看到如何解决这个问题吗?

提前致谢

<!DOCTYPE html>
<html lang="en">
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</head>
<body>
  <div id="testdiv" style="width:400px; height:400px; background-color:Beige;padding:40px;"> 
 <button id="openmodal" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">

  <!-- Modal content-->
  <div class="modal-content">
        <div class="modal-body">
      <p>Some text in the modal.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
  </div>

</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#testdiv").click(function(){
    alert("Only show when the outside area is clicked")
});
});

$(document).ready(function(){
$("#openmodal").click(function(){
event.stopPropagation();
    alert("Open the modal and only show this alert")
});
});

1 个答案:

答案 0 :(得分:0)

打开按钮单击模式并从button移除data-toggle="modal" data-target="#myModal"中的模态参考。使用.modal('show')打开按钮单击模式

&#13;
&#13;
$(document).ready(function() {
  $("#testdiv").click(function() {
    alert("Only show when the outside area is clicked")
  });

  $("#openmodal").click(function() {
    event.stopPropagation();
    $('#myModal').modal('show');
    alert("Open the modal and only show this alert")
  });
});
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>

<div id="testdiv" style="width:400px; height:400px; background-color:Beige;padding:40px;">
  <button id="openmodal" type="button" class="btn btn-info btn-lg">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>
</div>
&#13;
&#13;
&#13;