首页 > 解决方案 > 使用 Bootstrap 5.0.0 和 Webpacker 的动态模式

问题描述

从 Bootstrap 5.0.0 开始,似乎 Bootstrap JS 文件必须在最后加载<body>才能呈现动态加载的 Modals(可能还有其他功能)。在 GitHub 上查看此问题

同意这个问题。这发生在 bootstrap 5.x 生产版本中,无论您如何初始化模态。通过 JS 或通过 Data 属性动态地。

目前解决此问题的解决方法是bootstrap.bundle.js在 HTML 正文中而不是在头部中加载。但理想情况下,它不能解决这个问题。

你知道这个问题的另一种解决方法吗?


错误:
// Error happens when I want to display a Modal using JS

var modal = new bootstrap.Modal(document.getElementById('my-modal');
modal.show();

// Uncaught TypeError: BACKDROP: Option "rootElement" provided type "null" but expected type "element".
//    typeCheckConfig bootstrap.bundle.js:190
//    typeCheckConfig bootstrap.bundle.js:184
//    _getConfig bootstrap.bundle.js:4603
//    Backdrop bootstrap.bundle.js:4539
//    _initializeBackDrop bootstrap.bundle.js:4864
//    Modal bootstrap.bundle.js:4721
//    <anonymous> debugger eval code:2


一个解法:

<body>最简单的解决方法是在标签末尾加载我们的 JS :

# app/views/layout/application.html.erb

<body>
  <%= yield %>
  <%# this `javascript_pack_tag` is initially inside the `<head>` tag
  <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</body>

标签: javascriptruby-on-railstwitter-bootstrapwebpackruby-on-rails-6

解决方案


推荐阅读