Checkbox报错Cannot set properties of null (setting 'checked')
复选框状态持久化报错排查与修复方案
报错根因
Cannot set properties of null (setting 'checked') 触发的直接原因是JS执行时目标复选框DOM还未完成渲染,document.getElementById("checkboxFullDownload") 返回值为null,对null对象设置checked属性必然抛出错误。
除此之外代码存在3处逻辑错误:
- 变量作用域错误:
checkBox是_test函数内部声明的局部变量,函数外部的状态判断逻辑无法访问该变量;外部取值写的_test.item._id属于非法取值,_test是函数对象,本身不存在item属性。 - 冗余代码:
_test函数触发时已经能拿到复选框实时的checked状态,不需要重复手动给checkBox.checked赋值true/false。 - 生命周期冲突:你之前尝试的
window.onLoad方案如果和dojo组件加载周期冲突,会出现DOM还未挂载就执行选择逻辑的问题,导致拿不到元素。
可直接运行的修复代码
把原有JS替换为如下逻辑,将DOM操作、状态初始化统一放到DOM加载完成后执行,同时修正作用域问题:
document.addEventListener('DOMContentLoaded', function() { // 初始化阶段统一获取DOM,避免重复查询、避免时机错误返回null const checkBox = document.getElementById("checkboxFullDownload"); // 统一拼接localStorage存储key,避免多处拼写不一致 const storageKey = `${xmlTitle} ID:${this.item._id}`; // 页面加载时读取缓存,初始化复选框状态 if (localStorage.getItem(storageKey) === "AllowFullDownload") { checkBox.checked = true; console.log("set to true"); } // 复选框点击事件逻辑 function _test() { if (checkBox.checked) { console.log("Checked"); localStorage.setItem(storageKey, "AllowFullDownload"); } else { console.log("Unchecked"); localStorage.removeItem(storageKey); } } // 如果dojo自带的data-dojo-attach-event绑定不生效,解开下方注释手动绑定事件 // checkBox.addEventListener('change', _test); });
如果你使用的dojo框架版本较老,
DOMContentLoaded依然存在时机问题,可以改用dojo自带的ready回调确保组件和DOM完全挂载后再执行逻辑:require(['dojo/ready'], function(ready){ ready(function(){ // 将上述DOM获取、状态初始化、事件绑定逻辑移到此处即可 }); });
内容的提问来源于stack exchange,提问作者Jed
相关产品推荐
相关产品推荐

