" />

小言_互联网的博客

原生js最简化高效封装Cookie

380人阅读  评论(0)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>封装cookie</title>
</head>
<body>
    
</body>
<script src="./cookie.js"></script>
<script>
    const {cookie}= cookies; //引入声明一下
    cookie.set('maomin', '22', '0.5');
    console.log(cookie.get("maomin"));
</script>
</html>

cookie.js

const cookies = {
    cookie: {
    // 设置cookie
        set: (name, value, day) => {
            const date = new Date();
            date.setDate(date.getDate() + day);
            document.cookie = name + "=" + value + ";expires=" + date;
        },
    // 获取cookie
        get: (key) => {
            var arr = document.cookie.split("; ");
            for (var i = 0; i < arr.length; i++) {
                var arr1 = arr[i].split("=");
                if (arr1[0] == key) {
                    return arr1[1]
                }
            }
            return ""
        },
     // 删除cookie
        remove: (name) => {
            cookie.set(name,'', -1)
        }
    }

}

转载:https://blog.csdn.net/qq_39045645/article/details/103903438
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场