前面发表了一篇关于 cookie 的文章,封装了 cookie.js,下面我们通过一个实例来应用这个 js。
最常见的就是记住用户名,当用户登录过一次后,通过 cookie 记录下该用户的账号和密码,这样下次打开页面的时候不用再次输入账号密码了。附上代码:
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>cookie的应用——记住用户名</title> </head> <body> <form action="#" id="myform"> <label for="username">用户名:</label><input type="text" name="username" id="username" /> <label for="userpass">密码:</label><input type="password" name="userpass" id="userpass" /> <input type="submit" value="登录" /> <a href="javascript:;">清除记录</a> </form> </body> </html> <script type="text/javascript" src="cookie.js"></script> <script type="text/javascript"> window.onload = function(){ var oForm = document.getElementById('myform'); var oTxt1 = document.getElementById('username'); var oTxt2 = document.getElementById('userpass'); var oClear = document.getElementsByTagName('a')[0]; oTxt1.value = getCookie('username'); oTxt2.value = getCookie('userpass'); oForm.onsubmit = function(){ setCookie('username',oTxt1.value,30); setCookie('userpass',oTxt2.value,30); } oClear.onclick = function(){ removeCookie('username'); removeCookie('userpass'); oTxt1.value = ''; oTxt2.value = ''; } } </script>