【问题标题】:jQuery checkbox hide and show divjQuery复选框隐藏和显示div
【发布时间】:2017-09-11 15:51:29
【问题描述】:

我有这个工作的问题,一切都很好,但复选框不太好 如果我在重新加载后标记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>

【问题讨论】:

  • 不是问题,但您不需要在显示或隐藏方法中使用 0

标签: javascript jquery checkbox input


【解决方案1】:

这里有一个解决方案https://jsfiddle.net/441s41mt/1/

$('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');
<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>

首先,请参考jsfiddle,因为localStorage 将不适用于stackoverflow sn-p。

checkbox 中使用data-target 来引用类。

希望这会对你有所帮助。

【讨论】:

  • 嗨感谢这项工作完美我将类型更改为类因为这在页面上有很多复选框再次感谢
【解决方案2】:

我认为这是因为您将checkbox1checkbox2 绑定到localStorage 的同一个input 字段。也许这会有所帮助:

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

第二个复选框也有类似的东西。

【讨论】:

  • 是的,如果我为每个复选框加上这个命令,如果有任何想法,可能会使其成为小代码,这可能会更好,但非常感谢......这对我有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 2011-05-26
  • 2016-01-20
相关资源
最近更新 更多