保存的本地存储值但如何使用已保存的本地存储使用。我尝试创建一个函数 apply 但该类没有应用
document.querySelectorAll("#abc, #xyz").forEach(btn => {
btn.addEventListener("click", () => {
const e = document.querySelectorAll(".dog,.cat, #abc, #xyz");
e.forEach(el => {
el.classList.toggle("red");
var xyz = document.getElementById("xyz").className;
localStorage.setItem("vovo", xyz);
});
});
})
function apply(){
var xy = localStorage.getItem('vovo');
if (xy) {
var single = document.querySelectorAll(".dog,.cat, #abc, #xyz");
single.forEach(el => {
el.classList.add(xy);
});
}
};
功能逻辑:
button
按下a 时,我们检查它是否具有red
类(因为所有元素button
s 和其他div
s 将red
在某个时候接收该类)。
button
s 和其他div
s 中删除),因此localStorage
将存储类似“不,元素没有红色类”的内容。button
s 和其他div
s),因此localStorage
将存储类似“是的元素具有红色类”的内容。localStorage
将存储。'0'
'1'
现在,当页面刷新时,我们检查localStorage
存储red
类状态的项目是否存在(不存在null
)并且具有值,'1'
然后将该类应用于所有元素(button
s 和其他div
s)。
卸下固定项目red
从类状态localStorage
。
这是更新JavaScript
代码:
对不起大家,因为我无法使用 SO 的片段进行现场演示,
localStorage
因为代码是沙盒的。无论如何,这里有一个CodePen演示,说明了所需的功能。
const els = document.querySelectorAll('.dog,.cat, #abc, #xyz');
/** when the page finishes loading **/
document.addEventListener('DOMContentLoaded', () => {
/** check if the 'red' class was applied **/
applied = window.localStorage.getItem('class-applied') === '0' ? false:true;
/** remove "class-applied" item from the localStorage **/
window.localStorage.removeItem('class-applied');
/** if the "red" class was applied just apply it on document load **/
applied && els.forEach(el => el.classList.add('red'));
});
els.forEach(btn => {
btn.addEventListener('click', () => {
/** store the "red" class' state : '1' means it is applied, '0' means it isn't apllied **/
window.localStorage.setItem(
'class-applied',
!btn.classList.contains('red') ? '1' : '0'
);
els.forEach(el => el.classList.toggle('red'));
});
});
上面的代码应该放在
</body>
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句