cookie插件——cookie

使用cookie插件后,可以很方便地通过cookie对象保存、读取、删除用户的信息,还能通过cookie插件保存用户的浏览记录,它的调用格式为:

保存:$.cookie(key,value);读取:$.cookie(key),删除:$.cookie(key,null)

其中参数key为保存cookie对象的名称,value为名称对应的cookie值。

例如,当点击“设置”按钮时,如果是“否保存用户名”的复选框为选中状态时,则使用cookie对象保存用户名,否则,删除保存的cookie用户名,如下图所示:

在浏览器中显示的效果:

从图中可以看出,由于在点击“设置”按钮时,选择了保存用户名,因此,输入框中的值被cookie保存,下次打开浏览器时,直接获取并显示保存的cookie值。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>cookie插件</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="http://www.imooc.com/data/jquery-1.8.2.min.js"></script>
        <script src="http://www.imooc.com/data/jquery.cookie.js" type="text/javascript"></script>
    </head>
    
    <body>
        <div id="divtest">
            <div class="title">
                <span class="fl">cookie插件</span> 
                <span class="fr">
                    <input id="btnSet" type="button" value="设置" />
                </span>
            </div>
            <div class="content">
                <span class="fl">邮箱:</span><br />
                <input id="email" name="email" type="text" /><br />
                <input id="chksave" type="checkbox" />是否保存邮箱
            </div>
        </div>
        
        <script type="text/javascript">
            $(function () {
                if ($.cookie("email")) {
                    $("#email").val($.cookie("email"));
                }
                $("#btnSet").bind("click", function () {
                    if ($("#chksave").is(":checked")) {
                        $.cookie("email",$("#email").val(), {
                            path: "/", expires: 7
                        })
                    }
                    else {
                        $.cookie("email",null, {
                            path: "/"
                        })
                    }
                });
            });
        </script>
    </body>
</html>
原文地址:https://www.cnblogs.com/diaoniwa/p/6628970.html