【问题标题】:restore dropdown selection after refresh local storage刷新本地存储后恢复下拉选择
【发布时间】:2012-12-14 06:32:42
【问题描述】:

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

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

【问题讨论】:

    标签: javascript


    【解决方案1】:

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

     <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'];
        }
    

    【讨论】:

      【解决方案2】:

      因为您的选项值是整数,在这种情况下,我会检查选项的 ,而不是选项元素的文本内容。

      如果您有从零开始的递增数字选项值,这是一个可行的解决方案:

      DEMO

      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;
      }​
      

      【讨论】:

      • demo 效果很好,但是当我将它复制粘贴到我的项目中时,我得到“Uncaught TypeError: Cannot set property 'selected' of undefined”
      • 您应该为 localStorage 值添加一些检查。例如,如果您的 localStorage 的值为 4,您会收到这种错误,因为在此代码 sn-p 中没有索引为 4 的选项。
      【解决方案3】:

      在我看来,您将选择的 value 存储在本地存储中,但随后尝试使用选项 text 进行比较。也许我误解了您的应用程序是如何工作的。

      无论如何,这个 sn-p 应该可以正确选择您的值(对于番石榴果实):

      $("#fruit option[value='2']").attr("selected","selected");
      

      如果必须通过选项的文本设置选项标签(Guava):

      $("#fruit option").each(function(){
        if ($(this).text() == "Guava")
          $(this).attr("selected","selected");
      });
      

      【讨论】:

        猜你喜欢
        • 2012-07-10
        • 2022-06-17
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 2016-05-21
        • 2012-02-03
        • 2018-07-08
        • 2020-04-07
        相关资源
        最近更新 更多