如何使用javascript动态将引导程序模态附加到主体

时间:2018-11-20 12:35:43

标签: html bootstrap-modal

我有一个如下所示的引导程序模型,我想通过调用javascript函数addModal()将这种模式插入每个html页面;并且应该将modal附加到body标签 怎么做

<!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <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>

2 个答案:

答案 0 :(得分:1)

好的。现在,您只需要链接js文件,然后调用该函数即可。 (对于.append()方法,您仍然需要jquery)

function addModal() {
  $("body").append('<!-- Modal -->
    <div class="modal fade" id="myModal" role="dialog">
      <div class="modal-dialog">

        <!-- Modal content-->
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">Modal Header</h4>
            </div>
            <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>');
}

答案 1 :(得分:0)

一种简单的方法是使用jquery:

<script>
   $(document).ready(function() {
      $("#ModalDiv").load("yourModal.html");
   });
</script>

HTML:

<body>

   //your code

   <div id="ModalDiv"></div>

   //your code

</body>