我目前正在尝试使用 bootstrap 5 创建一个加载对话框。
所以我做的第一件事就是将文档中的对话框复制到我的测试 html 中:
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog" id = "waitDialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Some Stuff.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Understood</button>
</div>
</div>
</div>
</div>
然后我写了一些 JS 来尝试按照文档中的说明打开它
var myModal = document.getElementById('waitDialog');
var modal = bootstrap.Modal.getInstance(myModal)
modal.show();
这是直接来自 https://getbootstrap.com/docs/5.0/components/modal/#via-javascript 的文档
我不工作,因为模态为空。我做错了什么?
最佳答案
您的代码有两个问题。
首先,getInstance
方法返回与DOM元素关联的模态实例,因为它返回null
,这意味着模态还没有被初始化。
还有另一种方法 getOrCreateInstance
,如果没有找到实例,它应该创建实例 (https://getbootstrap.com/docs/5.0/components/modal/#getorcreateinstance)。
其次,模态元素是包含 div
的 modal
而不是 ID 为 waitDialog
的 div
。
理想情况下,您的代码应如下所示 https://jsfiddle.net/7m1oqc9d/3/
var myModal = document.getElementById('staticBackdrop');
var modal = bootstrap.Modal.getOrCreateInstance(myModal)
modal.show()
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog" id="waitDialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Some Stuff.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Understood</button>
</div>
</div>
</div>
</div>
关于javascript - 无法在 Bootstrap 5 中使用 JavaScript 打开 Modal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68217890/