javascript 页面刷新后保留下拉列表的选定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23171840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:28:55  来源:igfitidea点击:

Keep selected value of drop down list after page refresh

javascripthtmlrefreshbrowser-refresh

提问by user3148224

I have a button to filter a list based on the selections from several drop-down values. However I am running into an issue whereby once the button is clicked, the page refreshes and the drop-down values are reset to the default. How could I ensure that after the refresh, the selected values persist on the drop-down?

我有一个按钮可以根据几个下拉值的选择来过滤列表。但是我遇到了一个问题,一旦单击按钮,页面就会刷新,下拉值会重置为默认值。如何确保刷新后所选值仍保留在下拉列表中?

<div><select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
  </select>

   <select>
    <option value="ford">ford</option>
    <option value="chevy">Chevy</option>
    <option value="ram">Ram</option>
    <option value="jeep">Jeep</option>
   </select>

   <button id="button" onclick="filterMyList()">Filter</button>
  </div>

Any suggestions on how this could be handled? Thanks.

关于如何处理这种情况的任何建议?谢谢。

回答by Andrei CACIO

You can use the HTML5 localStorage api (http://www.w3schools.com/html/html5_webstorage.asp)

您可以使用 HTML5 localStorage api ( http://www.w3schools.com/html/html5_webstorage.asp)

Example for your case:

您的案例示例:

$(document).ready(function() {
    // On refresh check if there are values selected
    if (localStorage.selectVal) {
            // Select the value stored
        $('select').val( localStorage.selectVal );
    }
});

// On change store the value
$('select').on('change', function(){
    var currentVal = $(this).val();
    localStorage.setItem('selectVal', currentVal );
});

Hope this helps. Keep me posted.

希望这可以帮助。随时关注我。