我有持久的复选框,代表一周的日子。我能够将这些值存储在数组localStorage
中,以便它们在刷新后保留。
我想知道的是如何根据天数的选择输出“工作日”或“周末”?例如,用户选择“星期一”和“星期三”,输出是“工作日”
我已经使用案例对其进行了测试,但未能成功应用localStorage
的值。如何将我的值存储在数组中有什么问题吗?
我存储和保持值的功能:
function updateStorage() {
$checkboxes.each(function() {
formValues[this.id] = this.checked;
});
localStorage.setItem("formValues", JSON.stringify(formValues));
}
$checkboxes.on("change", function() {
updateStorage();
});
// On page load
$.each(formValues, function(key, value) {
$("#" + key).prop('checked', value);
});
答案 0 :(得分:0)
这是问题所在。一旦写入Localstorage,您需要删除该项目才能重新编写它
//checkbox
//function for persistent checkbox
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $("#checkbox-wrapper :checkbox");
function updateStorage(){
$checkboxes.each(function() {
formValues[this.id] = this.checked;
});
localStorage.removeItem('formValues');
localStorage.setItem("formValues", JSON.stringify(formValues));
}
$checkboxes.on("change", function(){
updateStorage();
});
// On page load
$.each(formValues, function(key, value) {
$("#output").html($("#output").html() + key + ": " + value + "<br/>")
});
我使用上面的代码更新了你的代码并且它可以正常工作。
答案 1 :(得分:0)
这是一个函数,它将检查你的days对象并返回一个具有2个布尔属性(isWeekDay
和isWeekendDay
)的对象:
function checkweekday(days) {
console.log('days', days);
var weekDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
var weekendDays = ['saturday', 'sunday'];
var isWeekDay = false;
var isWeekendDay = false;
for (var day in days) {
if (days[day]) {
if (day) {
if (weekDays.indexOf(day) > -1) {
isWeekDay = true;
}
if (weekendDays.indexOf(day) > -1) {
isWeekendDay = true;
}
}
}
}
return {
isWeekDay: isWeekDay,
isWeekendDay: isWeekendDay
}
}
从localStorage检索值后,使用该对象调用该函数。
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var check = checkweekday(formValues);
console.log(check);
答案 2 :(得分:0)
我希望你的意思是这样的
//checkbox
//function for persistent checkbox
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $("#checkbox-wrapper :checkbox");
function outputResult(isWeekday,isWeekend){
var output = ""
if( isWeekday && isWeekend ) output = "Both";
else if( isWeekday ) output = "Weekday";
else if( isWeekend ) output = "Weekend";
document.getElementById("output").innerHTML = output;
}
function checkDay(){
var isWeekday = false;
var isWeekend = false;
$checkboxes.each(function(){
if( this.checked ){
if( this.id == "saturday" || this.id == "sunday" ) isWeekend = true;
else isWeekday = true;
}
});
outputResult(isWeekday,isWeekend);
}
function updateStorage(){
$checkboxes.each(function(){
formValues[this.id] = this.checked;
});
localStorage.setItem("formValues", JSON.stringify(formValues));
checkDay();
}
$checkboxes.on("change", function(){
updateStorage();
});
// On page load
$.each(formValues, function(key, value) {
$("#" + key).prop('checked', value);
});