2015-04-25 80 views
-1

我試着寫兩個函數來設置和獲取的Cookie保存用戶喜歡的背景色:JavaScript的背景餅乾

function set_background_cookie(){ 
if (navigator.cookieEnabled) { 
    favColor = window.prompt("insert your favorite color please : " , "") ; 
    document.body.style.backgroundColor = favColor ; 
    document.cookie = "favoriteColor=" + favColor + ";" + "expires=Sat, 25 Apr 2020 12:11:05 GMT" ; 
    } 
} 

function get_background_cookie(){ 
var start , End , color ; 
var CookiesArray = document.cookie.split(';') ; 
start = CookiesArray[0].indexOf('='); 
End = start + CookiesArray.length ; 
color = CookiesArray[0].substring(start + 1 , End) ; 
document.body.style.backgroundColor = color ; 
} 

設置cookie是完美的,但我有一個問題,得到它 我的問題是什麼?

這是整個頁面:的

End = start + CookiesArray[0].length; 

代替:

<!DOCTYPE html> 

<html> 

<head> 

<script> 

function get_background_cookie(){ 
var start , End , color ; 
var CookiesArray = document.cookie.split(';') ; 
start = CookiesArray[0].indexOf('='); 
End = start + CookiesArray.length ; 
color = CookiesArray[0].substring(start + 1 , End) ; 
document.body.style.backgroundColor = color ; 
} 

function set_background_cookie(){ 
if (navigator.cookieEnabled) { 
    favColor = window.prompt("insert your favorite color please : " , "") ; 
    document.body.style.backgroundColor = favColor ; 
    document.cookie = "favoriteColor=" + favColor + ";" + "expires=Sat, 25 Apr 2020 12:11:05 GMT" ; 
    } 
} 

window.onload = function(){ 
set_background_cookie(); 
get_background_cookie(); 
} 




</script> 





</head> 

<body> 

</body> 

</html> 

回答

0

嘗試

End = start + CookiesArray.length ; 

你或許應該也檢查cookie的存在,而不只是假設cookie存在。否則,如果用戶禁用了Cookie,則可能會發生JavaScript錯誤。像這樣的事情應該這樣做:

function get_background_cookie() { 
    if (!document.cookie || !document.cookie.length) 
     return; 
    var CookiesArray = document.cookie.split(';'); 
    var start = CookiesArray[0].indexOf('='); 
    var End = start + CookiesArray[0].length; 
    var color = CookiesArray[0].substring(start + 1 , End); 
    document.body.style.backgroundColor = color; 
}