【问题标题】:Store and Load dropdown selection from localStorage从 localStorage 存储和加载下拉选择
【发布时间】:2014-12-03 03:17:46
【问题描述】:

我正在尝试将选项值保存到 localstorage,以便在打开不同页面或返回网站时保存选项并使用与上次打开网站时相同的 css 文件。

这是我到目前为止所做的,但我无法让它工作:

HTML:

<select name="style" id="style" onChange="changeCSS();">
    <option id="standard" value="standard">Standard</option>
    <option id="alternative" value="alternative">Alternative</option>
</select>

Javascript:

function changeCSS() {
    "use strict";
    var select, stylesheet, save;

    select = document.getElementById("style");
    stylesheet = document.getElementById("stylesheet");

    if(localStorage.getItem('save')) {
        select.options[localStorage.getItem('save')].selected = true;
    }

    if (select.value === "standard") {
        stylesheet.href = "include/global.css";
        localStorage.setItem('save', select.value);
    } else if (select.value === "alternative") {
        stylesheet.href = "include/alternative.css";
        localStorage.setItem('save', select.value);
    }
}

【问题讨论】:

    标签: javascript cookies local-storage


    【解决方案1】:

    设法让它最终工作。这就是我所做的:

    HTML:

    <select name="style" id="style" onChange="changeCSS();">
        <option id="standard" value="standard">Standard</option>
        <option id="alternative" value="alternative">Alternative</option>
    </select>
    

    将此添加到正文标记:

    <body onload="autoCSS();">
    

    Javascript:

    var select, stylesheet;
    
    function changeCSS() {
        "use strict";
    
        select = document.getElementById("style");
        stylesheet = document.getElementById("stylesheet");
    
        if (select.value === "standard") {
            stylesheet.href = "include/global.css";
            localStorage.setItem('save', select.value);
        } else if (select.value === "alternative") {
            stylesheet.href = "include/alternative.css";
            localStorage.setItem('save', select.value);
        }
    }
    
    function autoCSS() {
        "use strict";
    
        select = document.getElementById("style");
        stylesheet = document.getElementById("stylesheet");
    
        if (localStorage.getItem('save')) {
            select.options[localStorage.getItem('save')].selected = true;
            changeCSS();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多