输入用户名后, 会吧用户的姓名和摇出的点数和存入cookie中。 cookie只会保存对应用户最高的点数合。如果摇出更高的点数合,旧的就会被替换掉。通过查询按钮可以查询任意姓名的最高点数合记录。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>author:senDog 掷骰子游戏</title> </head> <body> 请输入用户姓名:<input type="text" > <button > play </button> 查询用户最高成绩<button >查询 </button> <script language="JavaScript" type="text/javascript"> /*封装骰子类*/ function shaizi(){ var num = parseInt(1+Math.random()*5); return{ "getNum":function(){ return num; }, "alertNum":function(){ alert("骰子点数:"+num); } }; } var s1 = new shaizi(); var s2 = new shaizi(); var x = document.getElementById("btn"); x.addEventListener("click",s1.alertNum); x.addEventListener("click",s2.alertNum); /*封装cookie类*/ function cookie(){ return{ /*把总点数存入客户端浏览器cookie,并设置每次关闭浏览器cookie消失*/ "addCookie":function(userName,num3){ var str = userName + "=" + escape(num3); document.cookie = str; //alert("str:"+str); }, "getCookie":function(userName){//获取指定名称的cookie的值 var strCookie=document.cookie; var arrCookie=strCookie.split("; "); for(var i=0;i<arrCookie.length;i++){ var arr=arrCookie[i].split("="); if(arr[0]==userName)return arr[1]; } return ""; } } } var ck = new cookie(); /*记录用户最高总点数,存入cookie,然后可以通过查询用户名查出用户最高点数的记录*/ function readName(){ userName1 = document.getElementById("userName1").value; } function ckSet(){ var num1=s1.getNum(); var num2 = s2.getNum(); num3 = num1+num2; var n = ck.getCookie(userName1); if(n!=null && n<num3) ck.addCookie(userName1,num3); } function ckGetName(){ // var userName1 = document.getElementById("userName1").value; alert("username:"+userName1); } function ckGetNum(){ //var userName1 = document.getElementById("userName1").value; var num=ck.getCookie(userName1); alert("用户最高总点数:"+num); } x.addEventListener("click",readName); x.addEventListener("click",ckSet); x.addEventListener("click",ckGetName); x.addEventListener("click",ckGetNum); var y = document.getElementById("btn2"); y.addEventListener("click",readName); y.addEventListener("click",ckGetName); y.addEventListener("click",ckGetNum); </script> </body> </html>
把代码复制到到TXT文档,后缀改为html即可运行。