检测bug写成完整的js代码 获取当前日期const today = new DatetoDateString; 获取当前页面使用次数let count = parseIntlocalStoragegetItempageCount 0; 解决bug 将字符串转换为数字 判断是否超过使用次数限制if count = 10 alert今天无法再使用本页面!; locationhref = 1
// 检测bug并修复 // 1. 变量today重复定义,应该删除第二个声明 // 2. localStorage的操作中,JSON.parse和JSON.stringify可能会抛出异常,应该加上try-catch语句处理
// 优化后的完整代码:
// 封装localStorage的操作方法 function getLocalStorageItem(key, defaultValue) { try { const value = localStorage.getItem(key); return value !== null ? JSON.parse(value) : defaultValue; } catch (error) { console.error(error); return defaultValue; } }
function setLocalStorageItem(key, value) { try { localStorage.setItem(key, JSON.stringify(value)); } catch (error) { console.error(error); } }
// 获取当前日期 const today = new Date().toDateString();
// 获取当前页面使用次数 let count = getLocalStorageItem('pageCount', 0);
// 判断是否超过使用次数限制 if (count >= 10) { alert('今天无法再使用本页面!'); location.href = '1.html'; } else { // 更新页面使用次数 setLocalStorageItem('pageCount', ++count); }
// 记录今天已经使用过页面 setLocalStorageItem('lastVisit', today);
原文地址: https://www.cveoy.top/t/topic/6GF 著作权归作者所有。请勿转载和采集!