正在尝试存档(要做的事情): 将复选框选择保存在localStorage >>中,这样用户就不必一次又一次地选中所有复选框。
问题: 我可以将选择保存在localStorage中,但是复选框未显示onload,该机制似乎也被颠倒了,而选中的复选框是 捕获了未经检查的等
我想念什么吗?
这是我的代码
// issue: if localStorage saves the checkbox, the input field will not display
$('input[type="checkbox"]').click(function () {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
});
function save() {
var checkbox = document.getElementById('activityTitleCb');
localStorage.setItem('activityTitleCb', checkbox.checked);
}
function load() {
var checked = JSON.parse(localStorage.getItem('activityTitleCb'));
document.getElementById("activityTitleCb").checked = checked;
}
function wis() {
location.reload();
localStorage.clear()
}
load();
.searchFilterBox{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="chiller_cb">
<input id="activityTitleCb" type="checkbox" class="searchFilterCb" value="activityTitleCb">
<label for="activityTitleCb"> add my name!</label>
</div>
<br>
<div class="col-sm-2 activityTitleCb searchFilterBox">
<input class="form-control input-sm" placeholder="add your name" id="inputsm" type="text">
</div>
<br>
<input type="button" id="ReserveerButton1" value="save checkbox choices" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="wis()"/>
答案 0 :(得分:0)
在函数加载中,尝试console.log(选中)以确保该值是布尔值。 您也可以尝试打开浏览器控制台以查看本地存储中存储了什么值。
答案 1 :(得分:0)
这是一个解决方案。您无需按下“保存”按钮,因为它会自动将其保存到localStorage。
https://codepen.io/anon/pen/PyKJQq
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// issue: if localStorage saves the checkbox, the input field will not display
$(() =>{
$('input[type="checkbox"]').change(function() {
if (this.checked) {
localStorage.setItem('activityTitleCb', true);
} else {
localStorage.setItem('activityTitleCb', false);
}
});
function save() {
var checkbox = document.getElementById('activityTitleCb');
localStorage.setItem('activityTitleCb', checkbox.checked);
}
function load() {
var checked = localStorage.getItem('activityTitleCb') === undefined ? false : localStorage.getItem('activityTitleCb');
checked = (checked === 'true');
document.getElementById("activityTitleCb").checked = checked;
}
function wis() {
location.reload();
localStorage.clear()
}
load();
})
</script>
<style>
.searchFilterBox{
display: none;
}</style>
<div class="chiller_cb">
<input id="activityTitleCb" type="checkbox" class="searchFilterCb" value="activityTitleCb">
<label for="activityTitleCb"> add my name!</label>
</div>
<br>
<div class="col-sm-2 activityTitleCb searchFilterBox">
<input class="form-control input-sm" placeholder="add your name" id="inputsm" type="text">
</div>
<br>
<input type="button" id="ReserveerButton1" value="save checkbox choices" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="wis()"/>