在JavaScript中使用Cookie保持复选框状态 [英] keep checkbox state using cookie in javascript

查看:105
本文介绍了在JavaScript中使用Cookie保持复选框状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否在JavaScript中给我一个示例代码,说明如何在刷新页面时通过创建cookie来保持复选框的状态?

我有以下内容,但是我无法按预期运行它.我是JavaScript新手.

Can you please give me an example code in JavaScript on how to keep the state of a checkbox by creating cookie when I refresh the page?

I have something as the following but I couldn''t manage have it run as I expected. I am new in JavaScript.

/*** Simple interface to cookie ***/
Something.Cookie = function (cookieName, defaultValue) {
    function createCookie(name, value, days) {
        var expires = "";
        var date;
        if (days) {
            date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split('';'');
        var c;
        for (var i = 0; i < ca.length; i++) {
            c = ca[i];
            while (c.charAt(0) === '' '') {
                c = c.substring(1, c.length);
            }
            if (c.indexOf(nameEQ) === 0) {
                return c.substring(nameEQ.length, c.length);
            }
        }
        return null;
    }
    this.read = function () {
        var val = readCookie(cookieName);
        Something.log("Read " + val + " from cookie " + cookieName);
        return val;
    };
    this.readBoolean = function () {
        return this.read() === "true";
    };
    this.write = function (value) {
        createCookie(cookieName, value, 365);
    };
    this.writeBoolean = function (value) {
        value ? this.write("true") : this.write("false");
    };
    if (this.read() === null) {
        this.write(defaultValue);
    }
    return this;
};




注意:




Note:

onclick="GM_setValue("document.myform.mybox.value","true")

可能也是一种解决方案,而不是使用cookie.
但是,不能在onclick函数中调用GM_setValue.
使用GM_setValue的解决方案也将有所帮助,因为我主要将此代码编写为Greasemonkey.



谢谢,

Artug

could also be a solution instead of using cookies.
However, GM_setValue cannot be called within onclick function.
A solution with GM_setValue would also be helpful because I mainly write this code in Greasemonkey.



Thanks,

Artug

推荐答案

页面上有多个复选框.我想在每次访问页面时保持其状态.

谢谢
I have multiple checkboxes on the page. I want to maintain their states every time I visit the page.

Thanks,


这篇关于在JavaScript中使用Cookie保持复选框状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆