javascript - 使用 Javascript 在 HTML 中刷新后保留选项

标签 javascript html local-storage

在使用本地存储进行刷新后,我尝试在 HTML 中保留所选选项。我按照提到的例子 here 下面是我的代码。

document.getElementById("interface-output").onchange = function() {
  localStorage.setItem('selectedtem', document.getElementById("interface-output").value);
};

if (localStorage.getItem('item')) {
  document.getElementById("selectedtem").options[localStorage.getItem('selectedtem')].selected = true;
}
<div class="row" id="ott-redirect-interface-selector">
  <label>Output Interface</label><br>
  <select id="interface-output" class="browser-default">
    <option value="select">Select an interface</option>
    <option value="eth0">eth0</option>
    <option value="eth1">eth1</option>
  </select>
</div>

不幸的是,此设置在刷新后不会保留所选选项。请问有什么建议吗?

最佳答案

<html>
  <body>
    <div class="row" id="ott-redirect-interface-selector">
      <label>Output Interface</label><br>
      <select id="interface-output" class="browser-default">
        <option id="select" value="select">Select an interface</option>
        <option id="eth0" value="eth0">eth0</option>
        <option id="eth1" value="eth1">eth1</option>
      </select>
    </div>
    <script>
      document.getElementById('interface-output').onchange = function() {
        localStorage.setItem('selectedtem', document.getElementById('interface-output').value);
      };

      if (localStorage.getItem('selectedtem')) {
        document.getElementById('interface-output').options[localStorage.getItem('selectedtem')].selected = true;
      }
    </script>
  </body>
</html>

关于javascript - 使用 Javascript 在 HTML 中刷新后保留选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41174516/

相关文章:

javascript - 试图在表单提交上显示一个元素

javascript - 操作递归数组

javascript - JS DecodeURIComponent 在 Firefox 中返回空字符串(最新)

javascript - 检测对输入(onfocus)事件的关注是元素在 dom 中不存在,但使用 Vanilla (普通)javascript

html - 在 HTML 中显示街道地址的最语义方式是什么?

sql - Web SQL 数据库或索引数据库 API ... 或两者兼而有之?

javascript - 如何检测有多少 Rest 项目可用

html - 防止 HTML Select Dropdown 扩展到最长的字符串

javascript - LocalStoragephonegap相机图像

google-chrome - Chrome扩展程序的 'chrome.storage.local'数据保存在哪里?