jQuery复选框隐藏并显示div

时间:2017-09-11 15:51:29

标签: javascript jquery checkbox input

我有问题这项工作,一切都很好,但复选框不太好 如果我在重新加载后标记checkbox1,则会标记checkbox2checkbox1。我必须帮助找到这项工作的方式。

仅保存复选框标记

$(function(){        
  $('#checkbox1')
    .prop('checked', localStorage.input === 'true')
    .on('change', function() {
      localStorage.input = this.checked;
      if (this.checked) {
        $('.column_category').show(0); //checked
      } else {
        $('.column_category').hide(0);
      }
    })
    .trigger('change');
});

$(function(){        
  $('#checkbox2')
    .prop('checked', localStorage.input === 'true')
    .on('change', function() {
      localStorage.input = this.checked;
      if (this.checked) {
        $('.column_sku').show(0); //checked
      } else {
        $('.column_sku').hide(0);
      }
    })
    .trigger('change');
});


<input type="checkbox" id="checkbox1"/><label for="cbxShowHide">Categories</label>
<input type="checkbox" id="checkbox2"/><label for="cbxShowHide">SKU</label>
<input type="checkbox" id="checkbox3"/><label for="cbxShowHide">UPC</label>

2 个答案:

答案 0 :(得分:0)

我认为这是因为您将checkbox1checkbox2绑定到input的{​​{1}}字段。也许这可以提供帮助:

localStorage

第二个复选框上有类似内容。

答案 1 :(得分:0)

您可以使用解决方案https://jsfiddle.net/441s41mt/1/

&#13;
&#13;
$('input[type="checkbox"]').each(function(){
  $(this).prop('checked', (localStorage.getItem($(this).attr('id')) === 'true') ? 'checked' : '')
});

$('input[type="checkbox"]')  
  .on('change', function() {
    localStorage.setItem($(this).attr('id'), this.checked);
    if (this.checked) {
      $('.' + $(this).data('target')).show();
    } else {
      $('.' + $(this).data('target')).hide();
    }
  })
  .trigger('change');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1" data-target="column_category"/><label for="cbxShowHide">Categories</label>
<input type="checkbox" id="checkbox2" data-target="column_sku"/><label for="cbxShowHide">SKU</label>
<input type="checkbox" id="checkbox3"/><label for="cbxShowHide">UPC</label>
&#13;
&#13;
&#13;

首先,请参阅jsfiddlelocalStorage将对stackoverflow代码段进行处理。

使用data-target中的checkbox来引用课程。

希望这会对你有所帮助。

相关问题