我是否必须为每个下拉菜单创建单独的Cookie?

时间:2016-01-03 20:23:02

标签: javascript html5

我是js的新手,但我设法创建了一个网站,其中包含一系列带有值(范围从1到10)的下拉菜单。如果用户搞砸了,或者重新加载/关闭浏览器,他们选择的任何值都将消失。我已经设法弄清楚如何在Firefox中使用本地文件创建Cookie - Chrome是一个失败的原因。

所以基本上,我确定如果用户重新加载页面,我可以弄清楚如何操作创建的cookie来预先选择下拉菜单条目,但是我是否必须对每个下拉列表执行此操作?

2 个答案:

答案 0 :(得分:2)

Cookie不适合纯粹的客户端信息,因为它们会附加到客户端到您网站的所有HTTP请求。

相反,我会使用web storagelocalStoragesessionStorage),has excellent support

您可以为要保存的每件事物创建一个具有属性的对象:

var settings = {
   a: "one",
   b: "two"
   // ...
};

每当您想要保存它时(例如,当用户更改内容时):

localStorage.settings = JSON.stringify(settings);

在页面加载时,要检索它:

var settings = JSON.parse(localStorage.settings || "null") || {
    a: "default",
    b: "default"
    // ...
};

然后使用settings.a等设置列表中的值。

答案 1 :(得分:1)

一种方法是在您的网址中使用#hash-bangs来完成此工作。一个简单的例子是:



$(function () {
  $("input").val(window.location.hash.substr(1)).keyup(function () {
    if (history.pushState) {
      history.pushState(null, null, '#' + $(this).val());
    }
    $("pre").text("Current URL is: " + window.location);
  });
  $("pre").text("Current URL is: " + window.location);
});

* {font-family: Segoe UI;}
pre {font-family: 'Consolas';}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="text" />
<pre></pre>
&#13;
&#13;
&#13;

您可以在此处查看输出: http://output.jsbin.com/yaheyurivi

如果您想存储和检索多个值,可以使用Serialize()执行此操作。创建多对键和值对象。让我们用两个输入尝试上面的相同例子。

&#13;
&#13;
$(function () {
  $("input").keyup(function () {
    if (history.pushState) {
      history.pushState(null, null, '#' + $("form").serialize());
    }
    $("pre").text("Current URL is: " + window.location);
  });
  // read the elements from the URL
  var theHash = location.hash.substr(1);
  // split the params
  theHash = theHash.split("&");
  // assign each
  for (i = 0; i < theHash.length; i++) {
    var inputName = theHash[i].split("=")[0];
    var inputValue = theHash[i].split("=")[1];
    $('input[name="' + inputName + '"]').val(inputValue);
  }
  $("pre").text("Current URL is: " + window.location);
});
&#13;
* {font-family: Segoe UI;}
pre {font-family: 'Consolas';}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  #1: <input id="text1" name="text1" /><br>
  #2: <input id="text2" name="text2" />
</form>
<pre></pre>
&#13;
&#13;
&#13;

直播示例:http://output.jsbin.com/qecilovoxu

其他方法包括LocalStorageCookies

相关问题