javascript (jQuery) 在 cookie 中单击时保存复选框状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13936865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:14:15  来源:igfitidea点击:

(jQuery) Save checkbox state on click in cookie

javascriptjqueryhtmlformsjquery-cookie

提问by user1913435

There are a lot of topics regarding this function, nonetheless I can't seem to get it working. I've googled on this specific case and a bunch of links let me here, but strangly enough I can't seem to get them to work. The only thing I did get working was the following: http://dl.dropbox.com/u/2238080/a/!old/z.htmbut as you can see, it doesn't store the state of the box is unchecked.

有很多关于这个功能的话题,但我似乎无法让它工作。我在这个特定案例上用谷歌搜索过,一堆链接让我在这里,但奇怪的是我似乎无法让它们工作。我所做的唯一工作是以下内容:http: //dl.dropbox.com/u/2238080/a/!old/z.htm但正如您所看到的,它不存储盒子的状态是未经检查。

Regards, Ruben

问候, 鲁本

回答by Mark Schultheiss

You can change ALL your code to just: EDITED to remove part unneeded.

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

including getting rid of all these:

包括摆脱所有这些:

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

EDIT: less verbose version:

编辑:不那么冗长的版本:

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

working example: http://jsfiddle.net/R73vy/

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

回答by Chris Halcrow

If you don't strictly need to use cookies, using the newer HTML5 Web Storage (specifically the sessionStorage object in this case) is a lot easier and better than storing in a cookie:

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

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

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

Browser support is pretty full:

浏览器支持非常完整:

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

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

回答by JaseC

If you're just interested in one checkbox AND/OR you don't want to include the jQuery cookie plugin for this, here's two lines of code:

如果您只对一个复选框感兴趣和/或您不想为此包含 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');  }); 

This also doesn't use cookies so saves a couple bytes of bandwidth. Change to localStorage to extend lifetime of saved selection.

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

回答by devnull69

It should work with jQuery < 1.6 but starting with 1.6 you should change every appearance of .attr("checked")to .prop("checked")

应该用jQuery <1.6工作,但首先是1.6,你应该改变的每一次出场.attr("checked"),以.prop("checked")

EDIT: Changed the if condition for checking the cookie

编辑:更改了检查 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 });
                        }
                    );
                }
            );
        }