动态添加HTML并调用模式



我想动态地向我的身体添加一块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">&times;</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'作为身体的孩子。它不会从您的服务器加载" motal.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')

我混合了一些电话。我必须使用load(),但是在我的body中这样做会删除已经存在的所有内容,所以我添加了一个容器:

$('body').append("<div id='messageboxContainer'></div>");
$('#messageboxContainer').load("modal.html");

正如其他人所指出的,您对.append()的使用不正确,因为在您的示例中,它实际上只会输出文本'modal.html'。加载模态的触发因素也将失败,因为您正在加载DOM外的模态HTML模板。一个简单的解决方案将如下:

$.ajax({
  url: 'modal-template.html',
  success: function(data) {
    $('body').append(data);
    $("#modal-id").modal();
  }
});

在上面的代码中,我们使用jQuery的内置AJAX支持来加载您的HTML模板。在成功的负载下,我们将这些信息作为data并将其附加到body。那时,您的模态及其相关ID现在存在于DOM中,因此我们触发了模态。

但是
<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>

从那里,您可以根据需要将内容插入模式:

$('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时)。就像我说的那样...这种方法只是我的偏好,因为它保留了已经是DOM的一部分的ID。您可以将其他数据属性传递给它,也更加灵活(仅,仅,仅是意见)。在我的正常用法中,我还传递了一个尺寸属性,以确定模式的大小。

最新更新