JS-记住用户名【cookie封装引申】
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>调用封装好的cookie文件来制作小案例</title> 6 <script src="cookie.js" type="text/javascript" charset="utf-8"></script> 7 </head> 8 <body> 9 <form action="" method="post" id="form1"> 10 <input type="text" name="user" id="user" value="56" /> 11 <input type="password" name="pass" id="pass" value="" /> 12 <input type="submit" value="提交" id="btn"/> 13 </form> 14 15 </body> 16 <script type="text/javascript"> 17 var oTxt1 = document.getElementsByName('user')[0], 18 oForm1 = document.getElementById('form1'), 19 oBtn = document.getElementById('btn'); 20 oForm1.onsubmit = function(){ 21 setCookie('user',oTxt1.value,14); 22 } 23 oTxt1.value = getCookie('user'); 24 </script> 25 </html>
cookie.js
1 /*****设置cookie*****/ 2 function setCookie(name, value, iDay) { 3 var oDate = new Date(); 4 oDate.setDate(oDate.getDate() + iDay); 5 document.cookie = name + '=' + value + ';expires=' + oDate; 6 } 7 /*****获取cookie*****/ 8 function getCookie(name) { 9 var arr = document.cookie.split("; "); 10 for(var i = 0; i < arr.length; i++) { 11 var arr2 = arr[i].split("="); 12 if(arr2[0] == name) { 13 return arr2[1] 14 } 15 } 16 return "" 17 } 18 /*****移除cookie*****/ 19 function removeCookie(name) { 20 setCookie(name, 1, -1); 21 };
越努力,越幸运;阿门。