javascript - 刷新页面后将类保存到图标
问题描述
我有这个代码:
<div class="places-item">
<div class="places-item-img"></div>
<div class="places-item-header">
<h2>Machu Picchu, Peru</h2>
<div class="places-item-header-add"><svg xmlns='http://www.w3.org/2000/svg' width='512' height='512' viewBox='0 0 512 512'><path d='M352,48H160a48,48,0,0,0-48,48V464L256,336,400,464V96A48,48,0,0,0,352,48Z' style='fill:transparent;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px'/></svg></div>
</div>
</div>
<div class="places-item">
<div class="places-item-img"></div>
<div class="places-item-header">
<h2>Ciucaș Peak, Romania</h2>
<div class="places-item-header-add"><svg xmlns='http://www.w3.org/2000/svg' width='512' height='512' viewBox='0 0 512 512'><path d='M352,48H160a48,48,0,0,0-48,48V464L256,336,400,464V96A48,48,0,0,0,352,48Z' style='fill:transparent;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px'/></svg></div>
</div>
</div>
.places-item {
width: 100%;
}
.places-item-img {
width: 100%;
height: 350px;
background-color: cyan;
}
.places-item-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1em 0;
}
.places-item-header h2 {
font-size: 24px;
max-width: calc(100% - 38px);
}
.places-item-header-add {
width: 28px;
height: 28px;
cursor: pointer;
}
.places-item-header-add svg {
width: 100%;
height: 100%;
}
.places-item-header-add.added svg path {
fill: #000 !important;
}
var addBtn = document.querySelectorAll('.places-item-header-add');
for(i=0;i<addBtn.length;++i)addBtn[i].addEventListener('click',function(){
this.classList.toggle('added');
});
当您单击该图标时,它会变为黑色。刷新页面后,我该怎么做才能使单击的图标(可能有几个)变黑?我打算在 localStorage 做这个。
解决方案
特定于您的元素,添加 id 以便我们可以指定哪个项目是活动的。例子。
将 id 添加到您的项目标题。
<div id='peru' class="places-item-header-add">
并在加载窗口时检查本地存储中的值并更新项目类。
var addBtn = document.querySelectorAll('.places-item-header-add');
var items = JSON.parse(localStorage.getItem('selected_items')) || {};
for (i = 0; i < addBtn.length; ++i) {
if (items[addBtn[i].id]) {
addBtn[i].classList.add('added');
}
addBtn[i].addEventListener('click', function() {
this.classList.toggle('added');
if (this.classList.contains('added')) {
items[this.id] = true;
} else {
items[this.id] = false;
}
localStorage.setItem('selected_items', JSON.stringify(items));
})
}
检查这个小提琴 https://jsfiddle.net/uwqevc65/
推荐阅读
- c - 有人可以解释一下 maxBit 是什么吗?
- cmake - Cmake从项目路径链接共享库
- arduino - 如何知道 Arduino 是否因 WDT 超时而重新启动?
- .net - 在 Chrome 中禁用源面板
- mysql - 如何在具有异步和池的节点中使用 Mysql2 获取 MySQL 的 insertId?
- java - 延迟 UI 线程中的方法而不阻塞它
- python - 来自 csv 文件的 MQTT 消息
- python - matplotlib 中轴上的尴尬科学记数法
- visual-studio-code - 如何在客户端机器上使用 vscode 和无节点运行后台节点进程
- python - 如何在“QMainWindow”中滚动