页面刷新后如何保持复选框处于选中状态

Anu*_*pta -1 html javascript jquery input

因此,我尝试在页面刷新后保持选中复选框,而我正在使用以下脚本,但是当页面刷新时,会将所有其他复选框选中。 还请注意,输入是动态生成的,不能用硬编码编码,所以我不能将不同的ID输入不同的输入

jQuery(function(){
    var test = localStorage.input === 'true'? true: false;
    jQuery('input').prop('checked', test || false);
});

jQuery('input').on('change', function() {
    localStorage.input = jQuery(this).is(':checked');
    console.log(jQuery(this).is(':checked'));
});
Run Code Online (Sandbox Code Playgroud)

考虑以下复选框在代码中

<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 5

您可以将所有复选框另存为JSON数组,然后通过遍历该数组来还原它们。

jQuery(function(){
    if (localStorage.input) {
        var checks = JSON.parse(localStorage.input);
        jQuery(':checkbox').prop('checked', function(i) {
            return checks[i];
        });
    }
});

jQuery(':checkbox').on('change', function() {
    localStorage.input = JSON.stringify(jQuery(':checkbox').map(function() {
        return this.checked;
    }).get());
});
Run Code Online (Sandbox Code Playgroud)