我正在使用 localStorage 保存我的复选框状态,然后稍后重新渲染它们(当单击按钮时),下面的内容似乎在大多数情况下都有效;除了我的加载函数中出现错误 'cannot set check of undefined'
。
请注意,我的复选框并非来自标准 HTML 标记,它们是使用 javascript 动态调用的 - 也许有比使用 input.checked
更好的方法?
function checkSaver() {
user = JSON.parse(localStorage.getItem(user));
var inputs = document.querySelectorAll('input[type="checkbox"]');
user.userAchkData = [];
inputs.forEach(function(input){
user.userAchkData.push({ id: input.id, checked: input.checked });
});
localStorage.setItem(username, JSON.stringify(user));
console.log(JSON.stringify(user));
}
<小时/>
function load_() {
// get saved latest checkbox states, recheck
user = JSON.parse(localStorage.getItem(user));
var inputs = user.userAchkData;
inputs.forEach(function(input){
document.getElementById(input.id).checked = input.checked; // erroring here, cannot set checked of undefined
});
<小时/>
完全错误:(尽管它实际上是选中复选框?)源自上面的 = 符号之后。有什么指点吗?
未捕获类型错误:无法将属性“checked”设置为 null 在评估(eventHandlers.js:339) 在Array.forEach() 在load_(eventHandlers.js:338)
最佳答案
问题是您没有检查变量是否设置正确。
试试这个:
function load_() {
// get saved latest checkbox states, recheck
// but first lets define a default value.
const defaultData = { userAchkData: [] };
const localStorageData = JSON.parse(localStorage.getItem(user));
let user = localStorageData || defaultData;
let inputs = user.userAchkData;
inputs.forEach(function(input){
document.getElementById(input.id).checked = input.checked; // erroring here, cannot set checked of undefined
});
同样适用于保存
功能。
function checkSaver() {
const defaultData = { userAchkData: [] };
const localStorageData = JSON.parse(localStorage.getItem(user));
let user = localStorageData || defaultData;
let inputs = document.querySelectorAll('input[type="checkbox"]');
user.userAchkData = [];
inputs.forEach(function(input){
user.userAchkData.push({ id: input.id, checked: input.checked });
});
localStorage.setItem(username, JSON.stringify(user));
console.log(JSON.stringify(user));
}
关于javascript - 无法设置未定义的选中(使用本地存储保存复选框),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60287520/