使用cookie插件将JQuery cookie数据打印到控制台

时间:2016-01-04 12:55:08

标签: jquery cookies

我目前正在尝试使用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>

2 个答案:

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