常见修复代码:
javascript
// 检查数据是否存在
const data = localStorage.getItem('quotes');
console.log('存储的数据:', data); // 用 console.log 检查
// 确保解析正确
const quotes = JSON.parse(data) || [];
console.log('解析后的数组:', quotes);
// 确保渲染到正确位置
const container = document.getElementById('list');
if (container) {
container.innerHTML = quotes.map(q => \`<p>\${q}</p>\`).join('');
} else {
console.log('找不到容器元素!');
}数据存了但刷新后没了
现象:数据操作成功了,但刷新页面后数据消失。
排查清单:
| 可能原因 | 检查方法 | 解决方法 |
|---|---|---|
| 没有持久化存储 | 检查有没有用 LocalStorage | 数据变化时保存到 LocalStorage |
| 存储时机不对 | 检查保存代码是否执行 | 在数据变化后立即保存 |
| 加载时机不对 | 检查页面加载时是否读取数据 | 在页面加载时从 LocalStorage 读取 |
| 存储格式问题 | 检查存储的数据格式 | 用 JSON.stringify 存,JSON.parse 取 |
完整的存取示例:
javascript
// 保存数据
function saveQuotes(quotes) {
localStorage.setItem('quotes', JSON.stringify(quotes));
}
// 读取数据
function loadQuotes() {
const data = localStorage.getItem('quotes');
return data ? JSON.parse(data) : [];
}
// 页面加载时读取
document.addEventListener('DOMContentLoaded', function() {
const quotes = loadQuotes();
renderQuotes(quotes);
});
// 添加新数据时保存
function addQuote(newQuote) {
const quotes = loadQuotes();
quotes.push(newQuote);
saveQuotes(quotes); // 别忘了保存!
renderQuotes(quotes);
}交互问题通用排查口诀
看控制台 → 加 console.log → 检查时机 → 问 AI
- 看控制台:有红色错误吗?
- 加 console.log:代码执行到哪一步了?数据是什么?
- 检查时机:代码是在正确的时间执行吗?
- 问 AI:把相关代码和现象描述清楚