你好,我遇到了这个错误,当我登录时, cogo toast alert 没有显示在页面上,但当我注销时,它会显示在页面上,知道为什么它会这样做吗?我try 了多种操作,例如记录toastLiveExample和toastBody,但当我登录showToast("text-bg-success", ${username}, you have successfully signed in! Check out your <a href="/profile/${username}">profile</a>!);时它总是返回空

类型错误:无法读取空的属性(正在读取"classList ') 在showToast(toast.js:6:20) 在HTMLDocument.(登录?id=.)

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" re
  <div id="alert"></div>

   
  <!--bootstrap code-->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/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>

推荐答案

问题在于jQuery load()是同步的,因此showToasttoast.html添加到多姆之前运行,正如 comments 中正确指出的那样(而且它不属于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();

Javascript相关问答推荐

如何使用合并排序方法编写数组排序Polyfill

为什么我的useDispatch挂钩在这里设置不正确?

复合密钥查找在mongoDB中未按预期工作

TypScript:根据共享属性对项目进行分组并为其分配groupID

如何在我的Web应用程序中使用JavaScript显示和隐藏喜欢/不喜欢按钮?

在JavaScript中检索一些文本

在分区内迭代分区

是什么原因导致此Angular 16应用程序中类型错误时属性结果不存在?

React 17与React 18中的不同setState行为

从WooCommerce Checkout Country字段重新排序国家,保持国家同步

如何粗体匹配的字母时输入搜索框使用javascript?

空的结果抓取网站与Fetch和Cheerio

无法读取未定义错误的属性路径名''

VUE 3捕获错误并呈现另一个组件

当id匹配时对属性值求和并使用JavaScript返回结果

在Reaction中的handleSubmit按钮内,useSelector值仍然为空

如何在JAVASCRIPT中合并两组对象并返回一些键

获取';无法解决导入和导入";slick-carousel/slick/slick-theme.css";';错误

在表单集中保存更改时删除';禁用';

无法使用npm install安装react-dom、react和next