所以我想用这个代码调用一个函数 Local.getThis onload:
class Local {
getThis() {
let that;
if (localStorage.getItem('that') === null) {
that = [];
console.log(that);
localStorage.setItem('that', that);
} else {
that=JSON.parse(localStorage.getItem('that'));
console.log(that);
}
}
// DOM Load Event
document.addEventListener('DOMContentLoaded', Local.getThis)
但是什么都没有发生,没有错误。但是当我将“getThis”更改为 STATIC 时,它可以工作(输出:[])。它需要是静态的吗?
附言
设置后 = []; 我收到一个错误
'Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at HTMLDocument.getThis'
在下一次重新加载时,但我猜这可能是另一个问题。
编辑:
为了记录错误与此有关localStorage.setItem('that', that);
,它当然应该是localStorage.setItem('that', JSON.stringify(that));