创建一个欢迎 cookie

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function setCookie(cname,cvalue,exdays) {
  6. var d = new Date();
  7. d.setTime(d.getTime() + (exdays*24*60*60*1000));
  8. var expires = "expires=" + d.toGMTString();
  9. document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  10. }
  11.  
  12. function getCookie(cname) {
  13. var name = cname + "=";
  14. var decodedCookie = decodeURIComponent(document.cookie);
  15. var ca = decodedCookie.split(';');
  16. for(var i = 0; i < ca.length; i++) {
  17. var c = ca[i];
  18. while (c.charAt(0) == ' ') {
  19. c = c.substring(1);
  20. }
  21. if (c.indexOf(name) == 0) {
  22. return c.substring(name.length, c.length);
  23. }
  24. }
  25. return "";
  26. }
  27.  
  28. function checkCookie() {
  29. var user=getCookie("username");
  30. if (user != "") {
  31. alert("再次欢迎您," + user);
  32. } else {
  33. user = prompt("请输入姓名:","");
  34. if (user != "" && user != null) {
  35. setCookie("username", user, 30);
  36. }
  37. }
  38. }
  39. </script>
  40. </head>
  41.  
  42. <body onload="checkCookie()"></body>
  43.  
  44. </html>