我想动态地向我的身体添加一段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,然后在其上调用引导方法?
发布于 2019-03-21 14:32:36
我把一些电话搞混了。我必须使用load(),但是在我的body中这样做会删除已经存在的所有内容,所以我添加了一个容器:
$('body').append("<div id='messageboxContainer'></div>");
$('#messageboxContainer').load("modal.html");发布于 2019-03-21 14:28:37
您正在执行的代码,即$('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')
发布于 2019-03-21 14:49:08
正如其他人所指出的,您对.append()的使用是不正确的,因为在您的示例中,它实际上只是输出文本“modal.html”。加载模式的触发器也将失败,因为您正在将模态HTML模板加载到DOM之外。一个简单的解决办法如下:
$.ajax({
url: 'modal-template.html',
success: function(data) {
$('body').append(data);
$("#modal-id").modal();
}
});在上面的代码中,我们使用jQuery的内置AJAX支持来加载HTML模板。在一个成功的加载中,我们将该信息作为data并附加到body中。此时,您的模式及其相关ID现在存在于Dom中,因此我们触发该模型。
然而,我个人的偏好是在默认的HTML中有一个“shell”模式:
<div class="modal fade" tabindex="-1" id="your-modal" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content"></div>
</div>
</div>然后,根据需要通过以下jQuery将内容插入到模型中:
$('body').on('click', '[data-toggle="modal"]', function(event) {
var m_target = $(this).data("target"),
m_path = $(this).attr("href");
$(m_target + ' .modal-content').load(m_path);
});
$('#your-modal').on('hidden.bs.modal', function (e) {
$(this).find('.modal-content').empty().html('');
$(this).modal('dispose');
});第一位允许您将模态内容加载到现有的空白模式模板中。第二种方法确保当模式关闭时,它被正确地清空,这缓解了下一个模式触发器可能加载缓存/旧信息的潜在问题(特别是当您链接到无效的URL时)。就像我说的。这个方法只是我的首选,因为它保留了一个ID,这个ID已经是DOM的一部分。它也更灵活一些(同样,仅限于意见),因为您可以将其他数据属性传递给它。在我的正常用法中,我还传递了一个size属性来确定Modal应该有多大。
https://stackoverflow.com/questions/55282508
复制相似问题