欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jquery.cookie的用法代码实例

程序员文章站 2022-06-29 12:33:47
jquery.cookie的用法代码实例 &...

jquery.cookie的用法代码实例

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
    <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>

    <title>次数存入cookie</title>
</head>
<body>
    <span>  </span>
    <br>
    <button id="add">
        clicknum++;
    </button>
    <button id="sub">
        clicknum--;
    </button>
<script>
    $(function () {
        var $add = $("button#add"),
            $sub = $("button#sub"),
            dialog =  "次数用尽了,明日再来哦";
        var clicknum = parseint($.cookie("clicknumcount"));  // 里面的值为string类型,转为数字
        console.log(clicknum)
        console.log(typeof clicknum);
        //做一个判断,是否有cookie存在,如果无测重新赋值10
        if((typeof(clicknum) === "number" && !isnan(clicknum)) || $.cookie("clicknumcount") == dialog ){
            console.log(clicknum);
            $("span").text($.cookie("clicknumcount"));
            console.log("有值,存入当前cookie");
        }else{
            clicknum = 10;
            $("span").html(clicknum);
            console.log("无值,重新赋值");
            $.cookie('clicknumcount', clicknum, { expires: 1 });
            $("#clicknum").html(clicknum);
        }
        $add.click(function() {
            if (clicknum > 0) {
                clicknum++;
                $("span").text(clicknum);   //赋值
                console.log(clicknum);
                $.cookie('clicknumcount', clicknum, { expires: 1 });  //存入
            } else {
                console.log($.cookie("clicknumcount"));
            }
        });
        $sub.click(function () {
            if (clicknum > 0) {
                console.log(clicknum);
                clicknum--;
                console.log(clicknum);
                $.cookie('clicknumcount', clicknum, {expires: 1});   //存入
                $("span").html(clicknum);   //赋值
            }else {
                $.cookie('clicknumcount', dialog, {expires: 1});   //存入
                console.log($.cookie("clicknumcount"));
                $("span").html(dialog);
            }
        });
    });
</script>
</body>
</html>

以上代码中可以直接复制到编辑器中,在上查看效果,用法不难,务必要快速脱离文档熟悉使用。