我目前正在尝试使用JQuery cookie插件在cookie userScoreCookie中存储变量userScore。当我在console.log中时,打印数据的内容是'undefined'。造成这种情况的原因是什么?
var cookieValue;
var userScore = 0;
$.cookie('userScoreCookie', 'userScore', {path: '/',expires: 365});
cookieValue = $.cookie("userScoreCookie");
console.log("cookie score: " + cookieValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
答案 0 :(得分:2)
将以下内容粘贴到链接以进行检查http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_hide
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
var cookieValue;
var userScore = 0;
$.cookie('userScoreCookie', "test");
cookieValue = $.cookie("userScoreCookie");
console.log("cookie score: " + cookieValue );
alert(cookieValue )
});
});
</script>
</head>
<body>
<p>Click me</p>
</body>
</html>
答案 1 :(得分:1)
Chrome页面在本地托管时无法使用Cookie,更改为firefox以测试已修复的Cookie