1

我在 localStorage 中存储了一些数据,我想动态输出这些数据(单击“之前”和“之后”箭头时)。我将页面重定向到自身并在文档准备好时显示当天的名称。

当我单击下一步时,天数会正确递增,但是当我之前单击时,天数不会正确递减,我尝试处理 (if 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;
}

您对我该如何解决有任何想法吗?

4

1 回答 1

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 也不需要重新加载页面。上面的例子是高度简化的,但我希望它能够理解并帮助你重新考虑你的方法。

于 2012-07-10T18:13:57.187 回答