簡體   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