zoukankan      html  css  js  c++  java
  • [javascript]在浏览器端应用cookie记住用户名

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <form action="http://www.baidu.com" id="frm">
            用户名<input type="text" name="" id="">
            密码<input type="password" name="" id="">
            <input type="submit" value="登陆">
            <a href="javascript:;" id="clear">清除记录</a>
        </form>
    
        <script>
            function setCookie (name, value, iDay){
                var oDate = new Date();
                oDate.setDate(oDate.getDate()+iDay);
                document.cookie = name+"="+value+";expires="+oDate;
            }
    
            function getCookie (name){
                var cookieArr = document.cookie.split("; ");
    
                for (var i = 0; i < cookieArr.length; i++) {
                    var oneCookie = cookieArr[i].split("=");
                    if (oneCookie[0] === name) {
                        return oneCookie[1];
                    }
                }
    
                return '';
            } 
    
            function removeCookie (name) {
                setCookie(name, '1', -1);
            }
    
            function addListener (target, type, handler) {
                if (target.attachEventListener) {
                    target.attachEventListener(type, handler, false);
                } else if (target.attachEvent) {
                    target.attachEvent("on"+type, handler);
                } else {
                    target["on"+type] = handler;
                }
            }
    
            window.onload = function (){
                var oForm = document.getElementById("frm");
                var oUser = oForm.getElementsByTagName("input")[0];
                var oClear = oForm.getElementsByTagName("a")[0];
                oForm.onsubmit = function (){
                    var username = oUser.value;
                    setCookie("username", username, 30);
                }
    
                oUser.value = getCookie('username');
    
                addListener(oClear, "click", function(){
                    removeCookie("username");
                    oUser.value = '';
                });
            }
        </script>
    </body>
    </html>

    只有在firefox下,可以直接用浏览器打开文件测试,所以建议上传至服务器端~

  • 相关阅读:
    Windows_10 系统封装
    leetcode-75 颜色分类
    leetcode-922 按奇偶排序数组 II
    leetcode-905 按奇偶数排序
    UVA-10827 环面上的最大子矩阵和
    leetcode918 环形最大子数组
    leetcode-85 最大矩形
    leetcode-84 柱状图中的最大矩形
    leetcode-221 最大正方形
    leetcode-713 乘积小于k的数组
  • 原文地址:https://www.cnblogs.com/zhongshanblog/p/4655624.html
Copyright © 2011-2022 走看看