You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap Alert自动关闭报错:Cannot read properties of null (reading 'defaultPrevented')

解决Bootstrap Alert自动关闭时的Uncaught TypeError错误

问题根源

你遇到的Uncaught TypeError: Cannot read properties of null (reading 'defaultPrevented')错误,本质是代码执行时找不到id="msg"的提示元素:

  • 当页面加载完成后,若当前页面没有渲染出提示框(比如用户还没执行创建博客/删除评论操作),document.getElementById("msg")会返回null。
  • 将null传入bootstrap.Alert构造函数后,调用close()方法时,内部会尝试用this._element(即null)触发事件,进而导致读取defaultPrevented属性失败。

修复代码

只需要在创建Alert实例前,先判断元素是否存在,再执行关闭逻辑:

document.addEventListener("DOMContentLoaded", () => {
  setTimeout(function () {
    let messages = document.getElementById("msg");
    // 检查元素存在后再执行关闭操作
    if (messages) {
      const alert = new bootstrap.Alert(messages);
      alert.close();
    }
  }, 2500);
});

额外优化点

  1. 动态提示框适配:如果提示框是用户操作后才动态生成的(比如后端渲染的提示),DOMContentLoaded触发时元素可能还不存在,可以改成监听元素的插入事件,或者把自动关闭逻辑绑定到提示框渲染完成的时机。
  2. 移除无用依赖:Bootstrap 5已不再依赖jQuery,你引入的jquery-3.3.1.slim.min.js可以直接删除,减少页面资源加载量。

内容的提问来源于stack exchange,提问作者cavedj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:31:17