提问人:Phil-Absynth 提问时间:10/6/2023 更新时间:10/6/2023 访问量:41
如何遍历 localStorage 以获取具有相同值的不同键?
How to iterate through localStorage for different keys with the same value?
问:
基本上,我有一个 HTML 表格作为时间表,其中包含工作日和每天内容的输入字段。每个输入都定义了一个 ID,并存储在 localStorage 中。当添加一个新输入并且已经存在于同一天的另一个输入中时,它会向两个输入添加一个类“双输入”。 我现在要做的是创建一个函数,该函数遍历所有作为表内容的 localStorage 项,以查找任何双重输入并通过添加类将它们标记为双重输入。
function getAnyDoubleInput() {
var week;
if (localStorage.getItem('currentWeek')) {
week = localStorage.getItem('currentWeek');
} else {
week = moment().isoWeek();
}
Object.keys(localStorage).forEach((key) => {
if (key.startsWith(week) && document.getElementById(key.substring(key.indexOf('_') + 1)).className == 'double-input') {
var keyValue = document.getElementById(key.substring(key.indexOf('_') + 1));
Object.keys(localStorage).forEach((newkey) => {
var newkeyValue = document.getElementById(newkey.substring(newkey.indexOf('_') + 1));
if(newkey.startsWith(week) && newkeyValue.className == 'double-input' && key != newkey) {
var weekDays = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag'];
weekDays.forEach(day => {
if (key.includes(day) && newkey.includes(day)) {
}
})
}
});
}
});
}
键和输入 ID 的简短说明:例如,ID 被创建为“tdMontag1”,存储此值的 localStorage 键将称为 40_tdMontag1(从周开始,因为每周都有表)。 我未能找到一种适当的方法来继续此函数(或创建一个全新的函数),以便在同一天将“double-input”类添加到所有双精度输入中,并将“no-double-input”类添加到没有双精度的输入中。 任何帮助将不胜感激,提前致谢。
答:
0赞
Ayoub k
10/6/2023
#1
function getAnyDoubleInput() {
let week;
if (localStorage.getItem('currentWeek')) {
week = localStorage.getItem('currentWeek');
} else {
week = moment().isoWeek();
}
// 1. Retrieve all relevant keys for the current week.
const weekKeys = Object.keys(localStorage).filter(key => key.startsWith(week));
// 2. Extract the input IDs and their values.
let inputs = {};
weekKeys.forEach(key => {
let id = key.substring(key.indexOf('_') + 1);
let value = localStorage.getItem(key);
if (inputs[id]) {
inputs[id].push(value);
} else {
inputs[id] = [value];
}
});
// 3 & 4. Identify duplicates and assign classes.
let weekDays = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag'];
weekDays.forEach(day => {
let dayInputs = Object.keys(inputs).filter(id => id.includes(day));
let duplicates = [];
dayInputs.forEach((id1, index1) => {
dayInputs.forEach((id2, index2) => {
if (index1 !== index2 && inputs[id1][0] === inputs[id2][0]) {
duplicates.push(id1, id2);
}
});
});
// Remove duplicates from the duplicates array.
duplicates = [...new Set(duplicates)];
// Add classes.
dayInputs.forEach(id => {
let element = document.getElementById(id);
if (duplicates.includes(id)) {
element.classList.add('double-input');
element.classList.remove('no-double-input');
} else {
element.classList.add('no-double-input');
element.classList.remove('double-input');
}
});
});
}
评论