开发者

How to make a javascript cookie that calls a function

So I am trying to implement cookies on my site, and I virtually have no experience with them (I have read with up on them though). The function below displays/keeps track of a users score in a simple game I'm dabbling with. What I am looking to do is make a cookie that will be able to remember one visitor and their score (Verify function). I only want to remember 1 user for simplicity's sake and for learning purposes. Hopefully that is clear. Thanks.

开发者_如何转开发
function Verfiy() {
    if ((positive+wrong) != 0) {
    score = "" + ((positive / (positive + wrong)) * 100);
    score = score.substring(0,4) + "%";
    alert("Here is your progress:  " + score + "\n"
    + positive + " positive\n"
    + wrong + " wrong")
}


You can cookie with data as below with javascript :

var date = new Date();
date.setTime(date.getTime()+(1*24*60*60*1000));
var expires = "; expires="+date.toGMTString();              
document.cookie = "fieldName=" + 'value here' + expires

You can read the value from cookie as below:

var ca = document.cookie.split(';');
var nameEQ = "fieldName=";
for(var i=0; i < ca.length; i++) {
   var c = ca[i];
   while (c.charAt(0)==' ')
      c = c.substring(1, c.length); //delete spaces
   if (c.indexOf(nameEQ) == 0) {
      value= c.substring(nameEQ.length, c.length);             
   }
}

This simple example to start. you could search web for more options

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜