使用localstorage将更改保存到后台

时间:2013-03-16 02:53:03

标签: javascript html5 local-storage

我正在尝试存储基于选择列表的用户点击所做的最新样式选择。我试图使用localstorage这样做,但我很难让它工作。

非常感谢任何帮助。谢谢!

在看了几个例子之后,这是我能想到的最好的 - 但它不起作用。

function initiate(){
    var styleButton = document.getElementById("selectStyleButton");
    if (styleButton){
        styleButton.addEventListener("click", saveStyle);
    }
    setStyle();
}

function saveStyle(){
    var select = document.getElementById("selectStyle");
    if (select){
        select[select.selectedIndex].value = localStorage.setItem("selectStyle"); //store value that was selected
    }
    setStyle(); //set the style that was selected based on the above
}

function setStyle(){
    var newstyle = localStorage.getItem("selectStyle"); //get value that was selected
    document.body.className = newstyle; //change body based on the class name of value that was selected
    }

window.addEventListener("load", initiate);

1 个答案:

答案 0 :(得分:0)

您在此处尝试执行的操作是设置所选选项的值,而不是将其存储在本地存储中。尝试改为

 localStorage.setItem("selectStyle",select[select.selectedIndex].value);

http://diveintohtml5.info/storage.html#methods