复选框启用/禁用DIV-本地存储-加载状态



我在index.html:中使用此复选框类型

<input class="check-1" type="checkbox" value="1" id="check-1"/>

这段代码在我的.js 中

$(".Categorie.1").show();
$(".check-1").click(function() {
if($(this).is(":checked")) {
$(".Categorie.1").hide();
} else {
$(".Categorie.1").show();
}
});
//localstorage
$('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');

当我加载页面时,没有问题,选中的复选框仍然是勾选的。但是DIV出现了。。。

有解决方案吗?

顺便说一句,我认为代码相当重。有可能制作一个更紧凑的版本吗?

非常感谢大家:-(

//fake out the localStorage for StackOverflow
var fakeLocalStorage = {
getItem: function ( key ) {
if ( key === 'check-1' ) {
return 'true';
}

return null;
}
};
$('.check-1').on('change', function() {
if (this.checked) {
$(".Categorie.1").hide();
} else {
$(".Categorie.1").show();
}
});
$('input:checkbox').each(function(){
var originalValue = this.checked;

this.checked = fakeLocalStorage.getItem(this.id) === 'true';

// Changing the value of the checked logically does not generate
// an event.  If you want to force the change listener to execute
// due to your change, you can logically trigger the event
if (originalValue != this.checked) $(this).trigger('change');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="check-1" type="checkbox" value="1" id="check-1">
<div class="Categorie 1">Show Me!</div>

这里有一个更完整的代码。

保存过程正常。刷新时,复选框始终处于选中状态。

但是,如果您检查删除红色或其他,刷新后,DIV会返回。

谢谢;-(

$("input[type=checkbox]").each(function() {
var name = $(this).attr('name');
if (localStorage.getItem(name) == "true") {
$(this).prop('checked', true);
}
});
$("input[type=checkbox]").change(function() {
var name = $(this).attr('name'),
value = $(this).is(':checked');
localStorage.setItem(name, value);
});
$('.togglebox').change(function () {
$("."+this.value).toggleClass('hide');
});
.one {
background: red;
}
.two {
background: green;
}
.three {
background: blue;
}
.four {
background: black;
}
.hide {
display: none;
}
<input class="togglebox" id="one-box" type="checkbox" name="boxes1" value="one" >First
<input class="togglebox" id="two-box" type="checkbox" name="boxes2" value="two" >Second
<input class="togglebox" id="three-box" type="checkbox" name="boxes3" value="three" >Third
<input class="togglebox" id="four-box" type="checkbox" name="boxes4" value="four" >Fourth
<div style="width: 300px; height: 100px;" class="one"></div>
<div style="width: 300px; height: 100px;" class="two"></div>
<div style="width: 300px; height: 100px;" class="three"></div>
<div style="width: 300px; height: 100px;" class="four"></div>

最新更新