簡體   English   中英

使用相同的代碼設置多個 cookie...使用 jQuery 或 JavaScript

[英]Set multiple cookies with the same code...using jQuery or JavaScript

我試過了,但我只能用我的代碼設置一個 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; } } }
 <!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>

我通過將 cookie 添加到一個對象來簡化迭代,為每個復選框添加一個 onchange,並將元素傳遞給我看:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM