繁体   English   中英

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

[英](jQuery) Save checkbox state on click in cookie

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

问候,鲁本

您可以将所有代码更改为: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
        });
    });
});

包括摆脱所有这些:

$(document).ready( function(){
    remember("[name=1]");
});
...

编辑:更简洁的版本:

$("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
    });
});

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

如果您不需要使用cookie,则使用较新的HTML5 Web存储(在本例中特别是sessionStorage对象)比存储在cookie中要容易得多,也更好:

http://www.w3schools.com/html/html5_webstorage.asp

浏览器支持非常丰富:

http://caniuse.com/#search=sessionstorage

如果你只对一个复选框感兴趣和/或你不想为此包含jQuery cookie插件,这里有两行代码:

//on page load set the checkbox to stored value or default to true
$('#turbo').prop('checked' , ( typeof sessionStorage.turbo !== 'undefined' ) ? (sessionStorage.turbo=='true') : true ); 
//when checkbox is updated, update stored value
$('#turbo').change( function() { sessionStorage.turbo = $(this).prop('checked');  }); 

这也不使用cookie,因此节省了几个字节的带宽。 更改为localStorage以延长已保存选择的生命周期。

它应该适用于jQuery <1.6,但从1.6开始你应该将.attr("checked")每个外观更改为.prop("checked")

编辑:更改了检查cookie的if条件

        function remember( selector ){
            $(selector).each(
                function(){
                    var name = $(this).attr('name');
                    if( $.cookie( name ) && $.cookie(name)=="true" ){
                        $(this).prop('checked', true);
                    } else {
                      $(this).prop('checked', false)
                    }
                    $(this).change(
                        function(){
                            $.cookie(name, $(this).prop('checked'), { path: '/', expires: 365 });
                        }
                    );
                }
            );
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM