我有一个javascript cookie,当用户进入网站时,它设置了NYY的默认值(不,是,是)。基本上,当用户从另一个页面中选择3个选项(收音机或复选框)的列表并记住他的设置时,我需要能够更改此默认值。
这是我的代码
<script type="text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function printCookies(w){
cStr = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0]){
cStr += NmeVal[0] + '=' + unescape(NmeVal[1]) + '; ';
}
}
return cStr;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function setTheDivStyle() {
if(!readCookie('preference')) {
// if cookie not found display the div and create the cookie
document.getElementById("prefBanner").style.display="block";
/*document.getElementById("prefBanner").style.display="block";*/
createCookie('preference', 'NYY', 365); // 365 day
}
else {
// if cookie found hide the div
document.getElementById("prefBanner").style.display="none";
}
}
// print all cookies set for the domain
allCookies = printCookies();
//document.write(allCookies);
alert(allCookies);
</script>
<body onload="setTheDivStyle();" onclick="setTheDivStyle();">
<div id = "prefBanner" class="prefCookie_banner">cookie policy banner - which the users sees if no cookie is set - to change your cookie preference <a href="newpage">click here</a></div>
新页面:我想要更改Cookie的默认值
<FORM NAME="profileForm">
Performance
<input type="radio" value="Y" id="performance" name="performance"><label for="performance"> Yes</label>
<input type="radio" value="N" id="performance" name="performance"><label for="performance"> No</label><br />
功能
是
没有
Tracking
<input type="radio" value="Y" id="tracking" name="tracking"><label for="tracking"> Yes</label>
<input type="radio" value="N" id="tracking" name="tracking"><label for="tracking"> No</label><br />
<input type="submit" >
</FORM>
答案 0 :(得分:0)
这会有效,但我不会这样做,但看看代码和制定的问题,这是最好的答案。
<input type="radio" value="Y" id="trackingY" name="tracking" onclick="createCookie('preference', 'Y', 365);">
<input type="radio" value="N" id="trackingN" name="tracking" onclick="createCookie('preference', 'N', 365);">
你的代码中有一些可怕的错误,不好意思直接但是如果你继续这样做,那么编写更大的功能将会很困难。
split函数返回一个数组,为什么在拆分
之前在变量上声明一个新数组pCOOKIES = new Array();
pCOOKIES = document.cookie.split(&#39;;&#39;);