gpt4 book ai didi

javascript - 从 localStorage 存储和加载下拉选择

转载 作者:行者123 更新时间:2023-11-30 05:30:41 25 4
gpt4 key购买 nike

我正在尝试将选项值保存到本地存储,以便在打开不同页面或返回网站时保存选项,并使用与上次打开网站时相同的 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);
}
}

最佳答案

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

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

关于javascript - 从 localStorage 存储和加载下拉选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27255469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com