复选框问题 - 无法设置null的属性(设置' checked')
大家好的一天,我目前在以下代码中面临一些问题。基本上,我想通过使用我存储在LocalStorage的键值对值来检查复选框,因此在重新加载时应检查复选框(具有键值对的复选框)。但是,我一直遇到这个错误。 我尝试使用window.onload,但它不起作用。还有其他解决方案。请让我知道我的代码是否有任何问题。谢谢您的
错误
Cannot set properties of null (setting 'checked')
HTML代码:
<div style="color: #005e95">
<input type="checkbox" id="checkboxFullDownload" data-dojo-attach-event="onClick: _test" style="cursor: pointer;" >
Full Download
</div>
JS代码:
_test: function() {
let checkBox = document.getElementById("checkboxFullDownload");
if (checkBox.checked) {
console.log("Checked");
localStorage.setItem(`${xmlTitle} ID:${this.item._id}`, "AllowFullDownload");
checkBox.checked = true;
}
if (!checkBox.checked) {
console.log("Unchecked");
localStorage.removeItem(`${xmlTitle} ID:${this.item._id}`);
checkBox.checked = false;
}
}
if (localStorage.getItem(`${xmlTitle} ID:${_test.item._id}`) === "AllowFullDownload") {
checkBox.checked = true;
console.log("set to true");
}
Good day everyone, I am currently facing some issues with my following code. Basically I want to keep my checkbox checked by using the key value pair value I stored in localStorage, so upon reload the checkbox should be checked (those with the key value pair). However, I kept getting this error.
I have tried using window.onLoad but it did not work; any other solutions for this..? Please do let me know if there is anything wrong with my code too. Thank you
Error
Cannot set properties of null (setting 'checked')
Html Code:
<div style="color: #005e95">
<input type="checkbox" id="checkboxFullDownload" data-dojo-attach-event="onClick: _test" style="cursor: pointer;" >
Full Download
</div>
JS Code:
_test: function() {
let checkBox = document.getElementById("checkboxFullDownload");
if (checkBox.checked) {
console.log("Checked");
localStorage.setItem(`${xmlTitle} ID:${this.item._id}`, "AllowFullDownload");
checkBox.checked = true;
}
if (!checkBox.checked) {
console.log("Unchecked");
localStorage.removeItem(`${xmlTitle} ID:${this.item._id}`);
checkBox.checked = false;
}
}
if (localStorage.getItem(`${xmlTitle} ID:${_test.item._id}`) === "AllowFullDownload") {
checkBox.checked = true;
console.log("set to true");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让
关键字是块范围,一旦在该范围之外无法访问范围内声明。在您的情况下,
让
关键字位于_test的范围:function(){}
。通过将其移到外面将完成工作。let
keyword is block scope once declared in scope cannot be accessed outside of that scope.In your case
let
keyword is in the scope of_test: function(){}
. By moving it outside will do the work.