gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:20:08 27 4
gpt4 key购买 nike

我试过了,但我只能用我的代码设置一个 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>

关于javascript - 使用相同的代码设置多个 cookie...使用 jQuery 或 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33430198/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com