gpt4 book ai didi

javascript - 刷新本地存储后恢复下拉选择

转载 作者:行者123 更新时间:2023-11-29 18:25:32 26 4
gpt4 key购买 nike

我正在尝试将选项标签值保存到本地存储。将其值保存到本地存储后,我希望能够将选项标签设置为用户选择的选项。我尝试了以下操作,但我只能保存该值。我无法将选择标签更改为用户选择的值。

<select name="fruit" id="fruit">
<option value="1">Apple</option>
<option value="2">Guava</option>
<option value="3">Mango</option>
<option value="4">Grapes</option>
</select>

document.getElementById("fruit").onchange = function() {
localStorage.setItem('fruit', document.getElementById("fruit").value);
}

if (localStorage.getItem('fruit') === "Guava") {
document.getElementById("fruit").setAttribute('Selected', 'Guava');
}

最佳答案

这是因为您选择的选项的值和文本不同。尝试:

 <select name="fruit" id="fruit">
<option value="Apple">Apple</option>
<option value="Guava">Guava</option>
<option value="Mango">Mango</option>
<option value="Grapes">Grapes</option>
</select>

document.getElementById("fruit").onchange = function() {
localStorage['fruit'] = document.getElementById("fruit").value;
}
window.onload= function(){
if(localStorage['fruit'])
document.getElementById("fruit").value = localStorage['fruit'];
}

关于javascript - 刷新本地存储后恢复下拉选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13873822/

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