Toast 函数找不到它的 div

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

您好,我遇到此错误,当我登录时,页面上没有显示 toast 警报,但在我注销时却显示了,您知道为什么会出现这种情况吗?我尝试了多种方法,例如记录 toastLiveExample 和 toastBody,但当我登录时它总是返回 null

showToast("text-bg-success", ${username}, you have successfully signed in! Check out your <a href="/profile/${username}">profile</a>!);

TypeError:无法读取 null 的属性(读取“classList”) 在 showToast (toast.js:6:20) 在 HTML 文档中。 (登录?id=...)

  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" re
  <div id="alert"></div>

   
  <!--bootstrap code-->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
  <!--alert code-->
  <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>

  <script>
    $("#alert").load("/staticHtml/toast.html");
  </script>
  <!-- toast function -->
  <script src="/js/toast.js"></script>

  <script>
    document.addEventListener('DOMContentLoaded', async () => {
      try {
        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        const token = urlParams.get("token");

        if (token) {
          const id = urlParams.get("id");
          const username = urlParams.get("username");

          let params = {
            _id: id,
            username,
            token,
          };

          showToast("text-bg-success", `${username}, you have successfully signed in! Check out your <a href="/profile/${username}">profile</a>!`);
          localStorage.setItem("user", JSON.stringify(params));
        }
      } catch (err) {
        console.log(err)
        showToast("text-bg-danger", "Something went wrong");
      }
    });
  </script>
function showToast(toastType, message) {
  const toastLiveExample = document.getElementById("liveToast");
  const toastBody = document.getElementById("toastBody");
  const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample);

  toastLiveExample.classList.add(toastType);
  toastBody.innerHTML = message;
  toastBootstrap.show();
}
<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div id="liveToast" class="toast align-items-center" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="d-flex">
      <div class="toast-body" id="toastBody">Hello, world! This is a toast message.</div>
      <i class="fa fa-times me-2 m-auto" data-bs-dismiss="toast" aria-hidden="true"></i>
    </div>
  </div>
</div>
javascript html bootstrap-5
1个回答
0
投票

问题是 jQuery

load()
是异步的,因此
showToast
toast.html
添加到 DOM 之前运行,正如评论中正确指出的那样(而且它也不属于
DOMContentLoaded
侦听器) ).

因此,您需要等待它加载,然后才运行您的代码。

一种快速而干燥的方法是发出同步请求:

$("#alert").html(
  $.ajax({
    type: 'GET',
    url: 'staticHtml/toast.html',
    async: false
}).responseText
);

或者你可以重构代码并使用 Promise,这有点冗长,例如:

function loadToast() {
    return new Promise(resolve => {
        $("#alert").load("staticHtml/toast.html", () => {
            resolve();
        });
    });
}


//...
document.addEventListener('DOMContentLoaded', async () => {

 await loadToast();
© www.soinside.com 2019 - 2024. All rights reserved.