2012-03-28 52 views
0

我有一個JavaScript cookie,它設置當用戶進入網站時的默認值NYY(不,是,是)。基本上我需要能夠改變這個默認值,當用戶從另一個頁面的3個選擇列表(收音機或複選框)中選擇並記住他的設置。Javascript cookie來存儲單選按鈕陣列

這裏是我的代碼

<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> 

NEWPAGE:在這裏我想更改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

那麼這將工作,但我不會那樣做,但看看代碼和公式化的問題,這是最好的答案。

<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);"> 

有一些可怕的錯誤代碼中的遺憾是直接的,但如果你繼續這樣它會是很難寫較大的作用。

  1. HTML無效:ID是唯一標識符,這意味着只有1個元素可以具有相同的ID。
  2. 使用大括號,他們應該去
  3. 使用var來聲明變量
  4. 分割函數返回一個數組,爲什麼聲明在新的變量數組分割

    pCOOKIES =新陣列前();

    pCOOKIES = document.cookie.split(';');