编程语言
首页 > 编程语言> > 单击链接,通过JavaScript打开Bootstrap 4 Modal

单击链接,通过JavaScript打开Bootstrap 4 Modal

作者:互联网

我想点击一个链接时打开一个模态.
不幸的是我无法更改链接的HTML.我只能改变href的内容.

像这样:

<a href="#Modal">Open modal</a>

我无法添加数据属性或任何其他HTML.

在文档中,我找到了一种通过JavaScript打开模态的方法.我将此代码添加到我的网站:

$('#Modal').modal();

它可以工作,但模式在页面加载后立即打开.
点击链接后我需要打开它.

有没有办法做到这一点?

这是我的模态:

<div class="modal" id="Modal" tabindex="-1" role="dialog" aria-labelledby="ModalTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <p class="h5 modal-title" id="ModalTitle">Modal Title</p>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                Content
            </div>
        </div>
    </div>
</div>

解决方法:

触发[href $=“#Modal”]上的点击事件.

$('a[href$="#Modal"]').on( "click", function() {
   $('#Modal').modal('show');
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<!-- Trigger the modal with a button -->
<a href="#Modal" class="btn btn-info btn-lg">Open modal</a>
<!-- Modal -->
<div id="Modal" class="modal fade" 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>

EIDT:将myModal更改为Modal

标签:html,bootstrap-modal,javascript,jquery,bootstrap-4
来源: https://codeday.me/bug/20190724/1521562.html