如何在.html文件中显示cookie的值

时间:2014-04-26 19:59:15

标签: javascript jquery html cookies

我有这个jquery:https://github.com/carhartl/jquery-cookie(jquery.cookie.js) 这是我的饼干:

$(document).ready(function(){

    //hide all divs just for the purpose of this example, 
    //you should have the divs hidden with your css

    //$('.picture.1').hide();
    //check if the cookie is already setted
    if ($.cookie("currentDiv")===undefined){
            $.cookie("currentDiv",1);
    } else{ //else..well 
            //get and increment value, let's suppose we have just 8 divs     

            var numValue = parseInt($.cookie("currentDiv"));
            numValue = numValue + 1;
            if (numValue>8){
            //restart to 1
                $.cookie("currentDiv",1);
            }
            else{ //no issues, assign the incremented value
                $.cookie("currentDiv",numValue.toString());
            }

            //show the div
            $('.picture.'+$.cookie("currentDiv")).show(0);
    }
});

名为currentDiv的cookie有一个从1到8的数字,当值高于8时,每次重新加载都会更改并重置

如何以当前值显示cookie(称为currentDiv)? 喜欢:

The installed cookies are:
   currentDiv with the value (for example 5)

2 个答案:

答案 0 :(得分:3)

你可以这样做列出所有页面的cookies:

<span id="myId"><span>
<script>
document.getElementById('myId').innerHTML=listCookies()
function listCookies() {
    var theCookies = document.cookie.split(';');
    var aString = '';
    for (var i = 1 ; i <= theCookies.length; i++) {
        aString += i + ' ' + theCookies[i-1] + "\n";
}
    return aString;
}
</script>

的jsfiddle:http://jsfiddle.net/5p34S/

答案 1 :(得分:0)

除非我误解,否则为cookie值显示创建一个元素,说它的ID是&#34; display-value&#34;。 在$(document).ready(function() { ... })中,将$("#display-value").text("The installed cookies are: currentDiv " + ($.cookie("currentDiv") || 0));添加到结尾(或开头,取决于您希望何时展示它)。