JQuery写Cookie读取Cookie删除Cookie(实例)

首次发布:2017-10-12 17:24

主要功能 写入Cookie与读取Cookie 

注意引用JQuery顺序  先引用主JQuery再引用JQuery.cookie.js

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <script src="lib/jquery/dist/jquery.js"></script>
    <script src="jquery.cookie.js"></script>
    <script type="text/javascript">
        $(function () {
            //写Cookie
            $('#btn1').click(function () {
                var user_name = $('#txt1').val();
                //{ expires: 7, path: '/', secure: false }这一部分功能是保存7天
                $.cookie('uname', user_name, { expires: 7, path: '/', secure: false });
            });
            //读取Cookie
            $('#btn2').click(function () {
                let user_name = $.cookie('uname');
                alert(user_name);
            });
            //删除Cookie
            $('#btn3').click(function () {
                $.removeCookie('uname', { path: '/' }); //path为指定路径,直接删除该路径下的cookie
            });
        });
    </script>
</head>
<body>
    用户名<input id="txt1" /><input type="button" value="记住用户名" id="btn1" />
    <input type="button" value="读取cookie" id="btn2" />
    <input type="button" value="删除cookie" id="btn3" />
</body>
</html>

视频讲解地址 https://www.bilibili.com/video/BV1jQ4y1C7pJ