javascript - 动态添加HTML并调用modal

标签 javascript jquery html twitter-bootstrap

我想将一段 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”作为 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/

相关文章:

javascript - 如何使用 Javascript 将键发送到输入文本字段?

javascript - 调用 async wait 时 undefined 不是一个函数

javascript - 动态创建文本区域和按钮

javascript - 使用三元表达式在两个字符串值之间切换的正确方法

javascript - 如何用javascript改变底部的样式?

javascript - 人们为什么使用原型(prototype)属性?

javascript - 如何让 Hedera JS SDK 正常关闭?

javascript - Jquery:+ 不能正常工作

html - 如何用css格式化输入框中的文本

php - Laravel:MethodNotAllowedHttpException 错误尝试点赞帖子