七天免登录JavaScript实现

版权声明:本文为博主原创文章,转载请声明出处,谢谢! https://blog.csdn.net/chengliang666/article/details/79966252

html代码

<label for="">用户名:</label><input type="text" id="username">
<label for="">密码:</label><input type="text" id="password">
<label for=""><input type="checkbox" id="check">7天免登陆</label>
<input type="button" value="登陆" id="btn">

JS代码

封装cookie

//设置cookie
function setCookie(_name, val, expires) {
    var d = new Date();
    d.setDate(d.getDate() + expires);
    document.cookie = _name + "=" + val + ";path=/;expires=" + d.toGMTString();
}

//获取cookie
function getCookie(_name) {
    var cookie = document.cookie;
    var arr = cookie.split("; ");
    for (var i = 0; i < arr.length; i++) {
        var newArr = arr[i].split("=");
        if (newArr[0] == _name) {
            return newArr[1];
        }
    }
}
  /*
        如何将json对象转换为字符串
            JSON.stringify(对象);
            返回值是一个字符串

        如何将字符串转换为json对象
            JSON.parse(字符串)
            返回值是对象

     */
    var oBtn = document.getElementById("btn");
    var oUser = document.getElementById("username");
    var oPass = document.getElementById("password");
    var oCheck = document.getElementById("check");

    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        oUser.value = cookie.name;
        oPass.value = cookie.pass;
        oCheck.checked = true;
    }

    oBtn.onclick = function () {
        if (oCheck.checked) {
            var obj = {};
            obj.name = oUser.value;
            obj.pass = oPass.value;
            var str = JSON.stringify(obj);
            setCookie("init", str, 7);
        }
    }
阅读更多

没有更多推荐了,返回首页