(jQuery)单击cookie保存复选框状态

use*_*435 6 html javascript forms jquery jquery-cookie

关于这个功能有很多主题,但我似乎无法让它发挥作用.我已经搜索了这个特定的案例,并且有一些链接让我在这里,但是绰绰有神,我似乎无法让他们工作.我唯一能做到的就是以下内容:http: //dl.dropbox.com/u/2238080/a/!old/z.htm, 但正如你所看到的,它不存储盒子的状态是选中.

问候,鲁本

Mar*_*iss 16

您可以将所有代码更改为:EDITED以删除不需要的部分.

$(document).ready( function(){
   // read the current/previous setting
    $("input.box[type=checkbox]").each(function() {
        var name = $(this).attr('name');
        if ($.cookie(name) && $.cookie(name) == "true") {
            $(this).prop('checked', $.cookie(name));
        }
    });
   // event management
    $("input.box[type=checkbox]").change(function() {
        var name = $(this).attr("name");
        $.cookie(name, $(this).prop('checked'), {
            path: '/',
            expires: 365
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

包括摆脱所有这些:

$(document).ready( function(){
    remember("[name=1]");
});
...
Run Code Online (Sandbox Code Playgroud)

编辑:更简洁的版本:

$("input.box").each(function() {
    var mycookie = $.cookie($(this).attr('name'));
    if (mycookie && mycookie == "true") {
        $(this).prop('checked', mycookie);
    }
});
$("input.box").change(function() {
    $.cookie($(this).attr("name"), $(this).prop('checked'), {
        path: '/',
        expires: 365
    });
});
Run Code Online (Sandbox Code Playgroud)

工作示例:http://jsfiddle.net/R73vy/

  • 我觉得值得一提的是那些偶然发现这个寻找答案的人,就像我一样,因为我花了一点时间研究才意识到这一点(这可能只是我自己的愚蠢,为此我道歉),但是你这将需要jquery.cookie插件才能运行.我在这个地址找到了它:https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js (2认同)