【问题标题】:jquery cookie script only remembers checkboxes and not radio buttonsjquery cookie 脚本只记住复选框而不是单选按钮
【发布时间】:2011-09-19 22:19:09
【问题描述】:

我有一个可以帮助我创建 cookie 的 js 脚本。它保存选中的复选框,以便记住该值(在 cookie 中设置)。现在的问题是它似乎不适用于单选按钮。阅读 js 文件时,我看到输入 type=checkboxes。所以它忽略单选按钮是合乎逻辑的。

如何更改此脚本,使其不仅会选中选中的复选框,还会选中选中的单选按钮?

非常感谢

我的js文件脚本:

    jQuery(document).ready(function(){

    new chkRemembrance();

});

function chkRemembrance(){
    this.__construct();
}

chkRemembrance.prototype = {

    __construct : function(){
        this.chk = this.fetchData(); // initialise array to store the checkboxes
        this.init();
    },

    init : function(){
        // first initialise all checkboxes that are checked
            for(c in this.chk){
                $("input[type=checkbox]#" + c).attr('checked', this.chk[c]);
            }
        // now make sure we fetch the checkbox events
        var o = this;
        $("input[type=checkbox]").change(function(){
            o.saveData(this.id, this.checked);
        })
    },

    fetchData : function(){
        var r = {};
        if ($.cookie('chk')){
            r = JSON.parse($.cookie('chk'));
        }
        return r;
    },

    saveData : function(id,status){
        this.chk[id] = status;
        $.cookie('chk', JSON.stringify(this.chk));
    }

}

【问题讨论】:

    标签: javascript jquery checkbox radio-button


    【解决方案1】:

    看起来您应该能够添加单选按钮并且它会起作用。

    改变这个:

    $("input[type=checkbox]#" + c).attr('checked', this.chk[c]);
    

    到这里:

    $("input[type=checkbox]#" + c + ", input[type=radio]#" + c).attr('checked', this.chk[c]);
    

    然后改变这个:

        $("input[type=checkbox]").change(function(){...});
    

    到这里:

        $("input[type=checkbox], input[type=radio]").change(function(){...});
    

    【讨论】:

    • 谢谢。我已经尝试过了,但它似乎不起作用。也许我的电台 html 是错误的? :<input type="radio" name="language" id="my_language" checked="" /> <input type="radio" name="language" id="en_language" checked="" />
    • 您可以尝试更改检查检查的行:o.saveData(this.id, this.checked); => o.saveData(this.id, $(this).attr('checked'));
    • 或者更确切地说,使用$(this).attr('checked') 的值来确定真/假。
    • 谢谢,但也没有运气。奇怪的是,清除cookie后,它第一次记住设置,秒时间(选择秒收音机)但是如果我在此之后再次选择第一个并刷新页面,它不再记得它并跳回(选择) 秒收音机又...奇怪
    猜你喜欢
    • 2011-11-04
    • 2014-02-12
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2010-10-27
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多