单击后退按钮时保留动态更改的选择值

时间:2017-03-06 14:39:26

标签: javascript jquery ajax

我有一个可以过滤不同车型的表格,而且它的工作非常完美。

当用户选择“Make”时,正确的兄弟“模型”将填充到下一个下拉列表中,依此类推。

问题在于,一旦用户执行了搜索,如果他们点击浏览器的后退按钮,则动态填充的选择值将恢复为默认值!

我没有使用ajax动态填充选择字段,但只使用javascript我正在阅读JSON文件并更新模型/系列/等。

我看过这篇文章:Preserve dynamically changed HTML on back button

我不明白这是如何运作的,我也听说过本地存储 - 对我来说,最好的旅程是什么?感谢。

2 个答案:

答案 0 :(得分:1)

由于数据是动态加载的,因此当用户返回上一页时,浏览器将无法重新填充先前选择的条目。

我建议您使用浏览器的localStorage存储最新的选项,并在用户返回时检索它们。要实现这一点,就像将一个新变量设置为localStorage对象并稍后检索它一样简单:

localStorage.make = "BMW";

alert(localStorage.make);

这里还有一个更有用的例子:

select = document.getElementById("make");

if (localStorage.make) {
    select.options[localStorage.make].selected = true;
}

答案 1 :(得分:1)

为此使用localStorage可能有点麻烦(何时以及如何清除此值?),并且有security related considerations可能使其成为不可行的解决方案。

另一种选择是使用隐藏的文本框,该文本框利用浏览器的默认行为。

在单击“后退”按钮后加载页面时,浏览器似乎会根据用户离开页面时所包含的值来填充文本框(即使该值是动态更改的)。 注意,这与处理隐藏输入(动态更改被忽略)的方式不同,因此必须使用文本框。

<select></select>
<input type="text" style="display:none" />

<script>
  // store the dropdown's value in a hidden textbox which is persisted and 
  // used to populate the dropdown when the back button is used to get here
  $('select').on('change', function() {
    $('input').val($(this).val());
  });

  // example showing dynamic population of dropdown
  $.ajax({
    url: 'api/get-dropdown-options',
    success: function(data) {
      // dynamically populate the dropdown
      $('select').html(data);

      // update the dropdown's value based on the persistent value
      // retained in the hidden textbox
      $('select').val($('input').val());
    }
  });
</script>