1

我正在尝试存储用户单击基于选择列表所做的最新样式选择。我曾尝试使用 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);
4

1 回答 1

0

您在这里尝试做的是设置所选选项的值,而不是将其存储在本地存储中。试试吧

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

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

于 2013-03-16T03:01:10.640 回答