我有一些数据存储在localStorage中,我想动态输出这些数据(当点击“之前”和“之后”箭头时)。我将页面重定向到自己&文档准备好后,显示当天的名称。
当我单击Next时,日期会正确递增,但是当我单击之前,日期没有正确递减时,我试图处理(如果counter = -1,counter = maxcounter)的情况,但它没有工作... 这就是我试过的:
使用Javascript:
function GetCurrentDay() {
if (localStorage["CurrentDay"] == null || localStorage["CurrentDay"] == 'NaN' || localStorage["CurrentDay"]=="undefined") {
localStorage["Counter"]= 0;
i = localStorage["Counter"];
localStorage["CurrentDay"] = localStorage["Day" + i];
}
return localStorage["CurrentDay"];
}
function GoToNextDay() {
var d = GetCurrentDay();
i = localStorage["Counter"];
i = i*1 + 1;
localStorage["Counter"] = i;
if(i!= localStorage["SchoolDays"]+1){
localStorage["CurrentDay"] = localStorage["Day" + i];
}else{
localStorage["CurrentDay"] = localStorage["Day" + 0];
}
return true;
}
function GoToPrevDay() {
var d = GetCurrentDay();
i = localStorage["Counter"];
i = i*1 - 1;
localStorage["Counter"]=i;
if(i>0){
localStorage["CurrentDay"] = localStorage["Day" + i];
}else{
i=localStorage["SchoolDays"];
localStorage["Counter"]=i;
localStorage["CurrentDay"] = localStorage["Day" + i];
}
return true;
}
您对如何解决这个问题有什么想法吗?
答案 0 :(得分:1)
我不太清楚我理解为什么你需要本地存储来显示和增加一天。如果没有关于您期望的行为的更多信息,很难给出完全明智的答案。首先,正如Bergi在评论中所说,你滥用本地存储。
例如,而不是:
function GetCurrentDay() {
if (localStorage["CurrentDay"] == null || localStorage["CurrentDay"] == 'NaN' || localStorage["CurrentDay"]=="undefined") {
localStorage["Counter"]= 0;
i = localStorage["Counter"];
localStorage["CurrentDay"] = localStorage["Day" + i];
}
return localStorage["CurrentDay"];
}
你可以这样做:
function GetCurrentDay() {
var currentDay = localStorage.CurrentDay;
if (!currentDay) {
var counter = 0;
currentDay = localStorage["Day" + counter];
}
localStorage.Counter = counter;
localStorage.CurrentDay = currentDay;
return currentDay;
}
上述方法要好得多,因为只有在需要获取或设置某些值时才能访问localStorage。中间的一切都发生在局部变量上,这将变得更快。此外,在可能的情况下,您应该使用点表示法来访问javascript对象。它的可读性更高。
现在,回到基本问题。你确定你需要localStorage吗?听起来你正在重新加载页面并使用localStorage来跟踪某些值。如果您避免这种情况并动态更新此日期字段,对您和您的访问者来说会容易得多。例如,假设您在页面的某个位置有这样的html结构:
<div id="day">0</div>
<span id="next">Next</span>
<span id="previous">Previous</span>
您可以收听点击事件并相应地更新。
var day = 0,
dayEl = document.getElementById('day');
document.getElementById('next').onclick = function() {
dayEl.firstChild.nodeValue = ++day;
}
document.getElementById('previous').onclick = function() {
dayEl.firstChild.nodeValue = --day;
}
无需localStorage,也无需重新加载页面。上面的例子是高度简化的,但我希望它能够解决问题并帮助您重新考虑您的方法。