我一直在努力解决这个问题,所以希望你们中的一些人能帮助我。 我拥有的网站有选项,您可以在其中选择网站的不同背景颜色,然后您选择的颜色存储在本地存储中。所以在你更新页面后,颜色会被保存。但是,我遇到的问题是您从中选择颜色的下拉菜单与您上次更改的颜色不同。
这就是我的意思。 这是我的 HTML 代码
<select id="selectcolor">
<option value="css/css.css" id="grey">Standard grått</option>
<option value="css/red.css" id="red">Häftigt rödigt!</option>
<option value="css/green.css" id="green"> Häftigt grön-svart! </option>
</select>
这就是我改变颜色后的样子
之后,当我刷新页面时,就会发生这种情况。颜色保持为红色,但选项变回标准颜色,而不是红色。
我试着用我的 javascript 代码动态地改变它,看起来像这样
var selectcolor = document.getElementById("selectcolor");
selectcolor.options[selectcolor.options.selectedIndex].selected = true;
但这似乎不起作用,我不明白为什么..? 非常感谢这里的一些帮助。
最佳答案
我注意到您在 selectcolor.option
中使用了 selectcolor.options.selectedIndex
.. 您的 localeStorage
变量在哪里?当我将 selectcolor.options.selectedIndex
的静态值更改为 2
时,它起作用了。我假设您的 localeStorage
变量是问题所在。
尝试将选定的索引存储在您的 localeStorage
变量中,然后执行此操作:
var selectcolor = document.getElementById("selectcolor");
selectcolor.options[yourLocaleStorageVariable].selected = true;
更新
<script>
function changeBg() {
var selectcolor = document.getElementById("selectcolor");
document.body.style.background = selectcolor.options[selectcolor.selectedIndex].value;
localStorage.setItem("selectedcolor", selectcolor.selectedIndex);
}
</script>
<select id="selectcolor" onchange="changeBg()">
<option value="" id="grey">Standard grått</option>
<option value="red" id="red">Häftigt rödigt!</option>
<option value="green" id="green"> Häftigt grön-svart! </option>
</select>
<script>
var selectcolor = document.getElementById("selectcolor");
if (localStorage.getItem("selectedcolor")) {
selectcolor.options[localStorage.getItem("selectedcolor")].selected = true;
document.body.style.background = selectcolor.options[selectcolor.selectedIndex].value;
}
<script>
尝试将你的逻辑建立在上面这段代码的基础上。希望这有帮助
关于javascript - 尝试在更新页面后动态更改所选属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48933335/