使用localStorage保存循环号码

时间:2014-05-12 18:56:00

标签: javascript local-storage

我一直试图在整个上午找到答案,似乎无法做到这一点。

当用户单击按钮时,想法是显示不同的数组项。问题是,一旦他们转到不同的页面,阵列将重置为0并重新开始。我希望它能够记住它在数组中的位置,并且即使用户访问了不同的页面也能够继续。

这是我到目前为止所做的,但如果我在点击按钮之前切换到不同的页面,它将会中断。

function iAmCarousel() {
    var describe = document.getElementById("describe");
    var describeArray = [];
        describeArray[0] = "Front End Web Developer";
        describeArray[1] = "Responsive Design nut";
        describeArray[2] = "Photoshop nerd";
        describeArray[3] = "soon to be husband";
    var refreshButton = document.getElementById("refresh");
    var index = localStorage.getItem("Index");

    describe.innerText = describeArray[index];

    refreshButton.onclick = function() {
        while(index < describeArray.length) {
            index++;
            localStorage.setItem("Index", index);
            if(index == describeArray.length) {
                index = 0;
            }
            describe.innerText = describeArray[index];
            break;
        }
    }
}
iAmCarousel();

1 个答案:

答案 0 :(得分:0)

因为&#34;索引&#34;不会在localStorage中设置,并且在不存在的键上调用getIndex()会返回null。您已离开了describeArray[null],但却无法工作(并会给您undefined)。

var index = localStorage.getItem("Index");

if (index === null) {
    index = 0;
}

describe.innerText = describeArray[index];

...或者你可以var index = localStorage.getItem("Index") || 0;(通过short circuit evaluation