javascript background cookie

时间:2015-04-25 14:34:04

标签: javascript cookies

我试图编写两个函数来设置并获取一个保存用户喜欢的背景颜色的cookie:

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是完美的但我遇到问题 我的问题是什么?

这是整个页面:

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

1 个答案:

答案 0 :(得分:0)

尝试:

End = start + CookiesArray[0].length;

而不是:

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