使用相同的代码设置多个cookie ...使用jQuery或JavaScript

时间:2015-10-30 06:44:58

标签: javascript jquery cookies

我试过但我只能用我的代码设置一个cookie ......它只需要进行一些修改。我还需要为保留复选框设置cookie ...如何使用

在通用模型中执行此操作



$(document).ready(function() {
  ReadCookie();
});

function setCookie(c_name, value) {
  document.cookie = c_name + "=" + value;
}

function set_check() {
  setCookie('Cookie1', document.getElementById('cookie_setter').checked ? 1 : 0);
  ReadCookie();
}

function ReadCookie() {
  var allcookies = document.cookie;
  // Get all the cookies pairs in an array
  cookiearray = allcookies.split(';');

  // Now take key value pair out of this array
  for (var i = 0; i < cookiearray.length; i++) {
    name = cookiearray[i].split('=')[0];
    value = cookiearray[i].split('=')[1];
    console.log("Key is : " + name + " and Value is : " + value);
    if (value == "1") {
      console.log(value);
      document.getElementById('cookie_setter').checked = true;
    }
  }
}
&#13;
<!DOCTYPE HTML>
<html>

<head>
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>

<body>
  <div style="max-width:980px;margin:0 auto;">
    <input type="checkbox" name="vehicle" id="cookie_setter" onchange="set_check();">Cookie1
    <br>
    <input type="checkbox" name="vehicle" value="Car">Cookie2
    <br>
    <input type="checkbox" name="vehicle" value="Car">Cookie3
  </div>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我通过将cookie添加到对象中简化了迭代,为每个复选框添加了onchange,并将元素传递给:

&#13;
&#13;
    function setCookie(c_name, value) {
      document.cookies = document.cookies || {};
      document.cookies[c_name] = value;
    }

    function set_check(e) {
      console.log(e.id)
      setCookie(e.id, document.getElementById(e.id).checked ? 1 : 0);
      ReadCookie();
    }

    function ReadCookie() {
      var allcookies = document.cookies;
      console.log(document.cookies)
      var div = document.getElementById('results');
      div.innerHTML = 'Results: ' + JSON.stringify(document.cookies);
    }
&#13;
<!DOCTYPE HTML>
<html>

<head>
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>

<body>
  <div style="max-width:980px;margin:0 auto;">
    <input type="checkbox"
        name="vehicle0"
        id="cookie1"
        onchange="set_check(this);">Cookie1
    <br>
    <input type="checkbox"
        name="vehicle1"
        onchange="set_check(this);"
        id="cookie2"
        value="Car">Cookie2
    <br>
    <input type="checkbox"
        name="vehicle2"
        onchange="set_check(this);"
        id="cookie3"
        value="Car">Cookie3
  </div>
  <br>
  <div id='results'></div>
</body>

</html>
&#13;
&#13;
&#13;