2014-12-02 73 views
1

我試圖將選項值保存到本地存儲,以便在打開不同的頁面或返回到網站時保存該選項並使用與上次時間相同的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); 
    } 
} 

回答

0

勉力讓它在最後工作。這是我做過什麼:

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(); 
    } 
}