javascript - 让复选框在整个 session 期间保持选中状态

标签 javascript jquery html checkbox session-storage

我有一个表格,我可以在其中选中一个复选框,它会记录该行中的所有内容。页面上有一些搜索功能和其他按钮,所以我想使用 session 存储能够在整个刷新过程中保留所有选中的复选框,直到页面关闭。我从我发现的一个例子中得到了一些东西,但它似乎没有用。我该如何解决这个问题?

带有复选框的表格列/行的 HTML:

<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid"></td>

JavaScript:

$(function(){
    var test = sessionStorage.input === 'false'? true: false;
    $('input').prop('checked', test || false);

    $('input').on('change', function() {
    sessionStorage.input = $(this).is(':checked');
    console.log($(this).is(':checked'));
});
});

最佳答案

看看这个:

var test = sessionStorage.input === 'false'? true: false;

那到底是什么意思呢?如果 sessionStorage.inputfalse,则返回 true,否则返回 false

因此,当您选中该复选框时,它会被设置为 true,根据上述逻辑,因为它不是 false - 测试被评估为 false.

解决方法:

var test = sessionStorage.input === 'true';

如果 session 也是 true,这会将测试设置为 true

您还可以将 $('input').prop('checked', test || false); 更改为:

$('input').prop('checked', test);

|| false 是不必要的。或者更好/更短:

$('input').prop('checked', sessionStorage.input === 'true');

然后您根本不需要 test 变量。

至于你的问题“我怎样才能让这个对单个复选框起作用”:你可以使用复选框 id 例如:

// save the individual checkbox in the session inside the `change` event, 
// using the checkbox "id" attribute
var $el = $(this);
sessionStorage[$el.prop('id')] = $el.is(':checked');

然后,当您刷新页面时:

$(':checkbox').each(function() {
    // Iterate over the checkboxes and set their "check" values based on the session data
    var $el = $(this);
    $el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
});

所以它应该是这样的:

$(function(){
    $('input:checkbox').each(function() {
        // Iterate over the checkboxes and set their "check" values based on the session data
        var $el = $(this);
        $el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
    });

    $('input:checkbox').on('change', function() {
        // save the individual checkbox in the session inside the `change` event, 
        // using the checkbox "id" attribute
        var $el = $(this);
        sessionStorage[$el.prop('id')] = $el.is(':checked');
    });
});

Working solution - 由于安全限制,它不支持 sessionStorage,因此无法使用堆栈片段。

关于javascript - 让复选框在整个 session 期间保持选中状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44118546/

相关文章:

javascript - 指定的 jQuery 函数不适用于新创建的项目

javascript - 如何在jquery中访问关联数组中的数组

javascript - 单击后更改按钮样式

javascript - jQuery 切换菜单,默认隐藏在 x 像素以下,如何实现?

jquery - 使用元素自身的宽度分配 margin-left

html - 启动图像不起作用

javascript - 使可拖动元素响应页面

javascript - 从下拉框中获取选定的值并用于填充文本框 php javascript

javascript - 表格行和表格单元格组合问题,偏移 1 个像素

jQuery textarea - 插入模式光标位置