简体   繁体   English

使用jQuery选中/取消选中单个复选框

[英]check / uncheck a single checkbox using jquery

I have a single HTML page with 30+ check boxes ( 我有一个包含30多个复选框的HTML页面(

How do I configure this script to remember only the check box I selected (Remember only that one checked or unchecked) 如何配置此脚本以仅记住我选中的复选框(仅记住该复选框已选中或未选中)

This is the script that I use: 这是我使用的脚本:

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

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

$('input') matches all inputs. $('input')匹配所有输入。 Give it a more specific selector (preferably the id of the input you want to remember. 给它一个更具体的选择器(最好是您要记住的输入的id

This code saves the state of all checkboxes between sessions: 此代码保存会话之间所有复选框的状态:

$('input[type=checkbox]').each(function(idx) {
  this.checked= localStorage.getItem('input'+idx) === 'true';
});

$('input[type=checkbox]').each(function(idx) {
  $(this).click(function() {
    localStorage.setItem('input'+idx, this.checked);
  });
});

Fiddle 1 小提琴1


If inputs are added, switched around, or deleted, you'll need a different method. 如果添加,切换或删除输入,则需要使用其他方法。

If each input has an id , you can use this code instead: 如果每个输入都有一个id ,则可以改用以下代码:

 $('input[type=checkbox]').each(function(idx) { this.checked= localStorage.getItem('input'+this.id) === 'true'; }); $('input[type=checkbox]').click(function() { localStorage.setItem('input'+this.id, this.checked); }); 

Fiddle 2 小提琴2

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

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