我想将一段 HTML 动态添加到我的正文中,然后使用它来显示模式窗口。 modal.html
是 Bootstrap 4 站点上示例的精确副本:
<div class="modal" tabindex="-1" role="dialog" id="dlgModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
我使用以下代码加载它:
$('body').append("modal.html");
当我检查 ID 是否存在时,我确实在开发人员控制台中找到了一个对象,但对其调用 modal()
没有效果:
» $("#dlgModal")
← Object { context: HTMLDocument http://127.0.0.1/index.html, selector: "#dlgModal" }
» $("#dlgModal").modal() /* nothing happens */
如何通过 Javascript 加载 HTML,然后调用其 Bootstrap 方法?
最佳答案
您正在执行的代码,即 $('body').append("modal.html");
,将简单地添加一个文本节点“modal.html”作为 body 的子节点。它不会从您的服务器加载“modal.html”文件。
假设 modal.html
文件由您的服务器提供 <hostname>/modal.html
,你的 JS 应该是这样的:
$.get('/modal.html', function(content) {
$('body').append(content);
});
$.get('/modal.html')
从您的服务器加载“modal.html”文件。从服务器加载文件时会执行回调函数,此时您可以将返回的内容附加到“body”中。
PS:要显示模式,您需要传递字符串 'show'
至.modal
功能。例如。 $("#dlgModal").modal('show')
关于javascript - 动态添加HTML并调用modal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55282508/