Bootstrap toast 警报:bootstrap 未定义

问题描述 投票:0回答:2

我正在使用开箱即用的 Bootstrap 5.3 创建吐司消息。控制台在这段代码中说:

const toastTrigger = document.getElementById('buynow')
const toastLiveExample = document.getElementById('liveToast')

if (true) {
  const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
  toastTrigger.addEventListener('click', () => {
    toastBootstrap.show()
  });
};

bootstrap 未定义。我很难过。我不知道我可以调整什么来修复这个错误。

  <!-- Scripts -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
  integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe"
  crossorigin="anonymous"></script>
  <script src="app.js"></script>
  <script src="https://kit.fontawesome.com/b20ad3118a.js" crossorigin="anonymous"></script>
</body>

</html>
javascript toast
2个回答
1
投票

您是否将“bootstrap”导入到您的组件中?

10 次中有 9 次出现未定义错误是因为组件或脚本中没有正确导入(或要求)某些内容。


0
投票

const toastTrigger = document.getElementById('buynow')
const toastLiveExample = document.getElementById('liveToast')

if (true) {
  const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
  toastTrigger.addEventListener('click', () => {
    toastBootstrap.show()
  });
};
<html>
<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css" />
</head>
<body>
  
  <button type="button" class="btn btn-primary" id="buynow">Buy Now</button>

  <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
    <div id="liveToast" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small>11 mins ago</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        Hello, world! This is a toast message.
      </div>
    </div>
  </div>
  <!-- Scripts -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
  integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe"
  crossorigin="anonymous"></script>
  <script src="app.js"></script>
  <script src="https://kit.fontawesome.com/b20ad3118a.js" crossorigin="anonymous"></script>
</body>

</html>

如果您正确导入库,此代码没有问题。我建议检查

Inspect Element > Network > JS
中的库是否成功导入,并确保所有状态都是
200
。确保您的互联网/代理不会阻止图书馆。

© www.soinside.com 2019 - 2024. All rights reserved.