我從Headfirst Javascript書中獲取了此代碼,用於cookie。但由於某種原因,它不適用於我的瀏覽器。我主要使用chrome和ff,並且我在Chrome中啓用了本地Cookie。幫幫我??Javascript Cookie代碼不存儲cookie /讀取空cookie值?
<script type="text/javascript">
function checkCookie(){
var name = eatCookie("yahooEmail");
if(name)
document.getElementById("emailVerf").style.visibility="hidden";
else
document.getElementById("emailBody").style.visibility="hidden";
}
function writeCookie(name, val, days){
var expires = "";
if(days){
var date = new Date();
date.setTime(date.getTime + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + val + expires + "; path=/";
}
function eatCookie(val){
var search = val + "=";
var cookies = document.cookie.split(';');
for(var i=0; i < cookies.length; i++){
var c = cookies[i];
while(c.charAt(0) == ' ')
c=c.substring(1, c.length);
if(c.indexOf(search) == 0)
return c.substring(search.length, c.length);
}
return null;
}
function verEmail(val){
var regex = "[a-zA-Z0-9][@yahoo.com]";
var exp = new RegExp(regex);
if(!exp.test(val)){
document.getElementById("email").style.color="red";
alert("Please enter a valid Yahoo email address.");
}
else{
writeCookie("yahooEmail", val, 7);
document.getElementById("emailVerf").style.visibility="hidden";
document.getElementById("emailBody").style.visibility="visible";
}
}
</script>
以何種方式是不工作?讀曲奇?寫曲奇?別處?你有什麼錯誤嗎? – mkilmanas 2011-06-13 13:38:10
@mkilmanas它不能讀取或寫入cookie。當我讀取cookie時,它返回null,所以每次我加載頁面時,它都像沒有cookie一樣。而雅虎是一個錯字,但我改變了它以前的狀況。即使拼寫正確,它也不起作用。 – banjokaboom 2011-06-15 14:26:52