问题描述
我正在尝试将选项标记值保存到本地存储。将其值保存到本地存储后,我希望能够将选项标记设置为用户选择的选项。我尝试了以下,但我只能保存价值。我无法将select标记更改为用户选择的值。
I am trying to save an options tag value to local storage. After saving its value to local storage I would like to be able to set the options tag to the option the user selected. I have tried the follow, but I am only able to save the value. I have trouble changing the select tag to the users selected value.
<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');
}
推荐答案
因为您的选项值是整数在这种情况下,我会检查选项的值,而不是选项元素的文本内容。
Because your option values are integers, in this case, I would check against the value of the option, not the textual contents of the option element.
这是一个解决方案,如果您有从0开始的增量数字选项值,则有效:
Here's a solution that works if you have incremental numerical option values, starting from zero:
HTML:
<select name="fruit" id="fruit">
<option value="0">Apple</option>
<option value="1">Guava</option>
<option value="2">Mango</option>
<option value="3">Grapes</option>
</select>
你的JS将是:
document.getElementById("fruit").onchange = function() {
localStorage.setItem('fruit', document.getElementById("fruit").value);
}
if (localStorage.getItem('fruit')) {
document.getElementById("fruit").options[localStorage.getItem('fruit')].selected = true;
}
这篇关于刷新本地存储后恢复下拉列表选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!