我对这段代码有疑问,请使用CS50的网络编程:
<script>
// Set starting value of counter to 0
if (!localStorage.getItem('counter'))
localStorage.setItem('counter', 0);
// Load current value of counter
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#counter').innerHTML =
localStorage.getItem('counter');
// Count every time button is clicked
document.querySelector('button').onclick = () => {
// Increment current counter
let counter = localStorage.getItem('counter');
counter++;
// Update counter
document.querySelector('#counter').innerHTML = counter;
localStorage.setItem('counter', counter);
}
});
</script>
LocalStorage是否在DOMContentLoaded之前加载? 在到达该行之前,我可以实际运行代码吗? 谢谢!
答案 0 :(得分:1)
可以。 localStorage方法是同步的,并且localStorage在窗口中立即可用。与DOM无关