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

Uncaught TypeError:无法读取null的classList属性(Django场景)

问题解决:Django模板中Toast提示报错"Cannot read properties of null (reading 'classList')"

这个错误的核心原因是你的页面里缺少.toast-ex类的Toast容器DOM元素,代码里用document.querySelector('.toast-ex')找不到元素,返回null后调用classList就会触发报错。按以下步骤修复:


1. 添加Toast容器HTML结构

在transaction.html的合适位置(比如body末尾、按钮附近)添加Bootstrap Toast的基础结构,必须包含.toast-ex类:

<div class="toast toast-ex" role="alert" aria-live="assertive" aria-atomic="true" style="position: fixed; top: 20px; right: 20px; z-index: 9999;">
  <div class="toast-header">
    <i class="ti ti-check me-2"></i>
    <strong class="me-auto">操作提示</strong>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="关闭"></button>
  </div>
  <div class="toast-body">
    点击按钮触发的Toast提示!
  </div>
</div>

注:添加position: fixed等样式是为了让Toast固定在页面角落,避免被其他元素遮挡

2. 修正JavaScript代码

原JS里存在未定义变量(比如toastPlacementExample)和逻辑冗余,修正后的代码如下:

$(document).ready(function(){
    $('.add-data').click(function (event) {
      const toastAnimationExample = document.querySelector('.toast-ex');
      // 定义需要用到的样式类
      const selectedType = 'text-success';
      const selectedAnimation = 'animate__fadeInRight';
      let toastAnimation;

      // 销毁已存在的Toast实例,避免重复弹出
      if (toastAnimation) {
        toastAnimation.dispose();
      }

      // 重置Toast的样式,防止重复添加类导致样式冲突
      toastAnimationExample.classList.remove(selectedAnimation);
      toastAnimationExample.querySelector('.ti').classList.remove(selectedType);
      
      // 添加新样式并显示Toast
      toastAnimationExample.classList.add(selectedAnimation);
      toastAnimationExample.querySelector('.ti').classList.add(selectedType);
      toastAnimation = new bootstrap.Toast(toastAnimationExample);
      toastAnimation.show();
    });
});

3. 检查依赖是否齐全

  • 确保已引入Bootstrap核心JavaScript(因为bootstrap.Toast是Bootstrap的组件,仅引入toastr.js不够)
  • 如果使用了animate__fadeInRight动画类,需要引入animate.css文件,否则动画不生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:48:35