javascript 如何在本地存储器中存储单击事件

km0tfn4u  于 2023-02-02  发布在  Java
关注(0)|答案(2)|浏览(137)

如何将单击事件存储在本地存储中,以便在页面刷新后使用。

const container = document.querySelector('.filter ul');

container.addEventListener('click',(event) =>{
  const closest = event.target.closest('.accordion-header');
  if (!closest) return;
  closest.classList.add('active');
  closest.nextElementSibling.classList.add('active');
});
<div class = "filter">
  <ul>
    <li>
     <h4 class = ""> Accordion </h4>
     <p> Hello,world </p>
    </li>

  </ul>
 </div>
gj3fmq9x

gj3fmq9x1#

听起来您并没有试图存储单击(事件),而是存储了该项目已被单击的事实,并通过页面刷新来存储它。
在单击处理程序中,需要添加一行代码,将单击状态存储到本地存储中。

localStorage.setItem('itemClicked', 'true');

注意localStorage只存储字符串,这里我们在sotrage中存储了一个名为itemClicked的项,并将其赋值为true
在页面加载时,您需要检查本地存储并再次对元素运行classList.add('active')

localStorage.getItem('itemClicked') === 'true';
igetnqfo

igetnqfo2#

你可以使用localStorage API,你可以在本地存储中保存每个可折叠头及其兄弟的活动类的状态,这样你就可以在页面刷新后检索它。

const container = document.querySelector('.filter ul');

container.addEventListener('click', (event) => {
  const closest = event.target.closest('.accordion-header');
  if (!closest) return;

  closest.classList.add('active');
  closest.nextElementSibling.classList.add('active');
  
  // Store the state of the accordion header and its sibling in local storage
  localStorage.setItem('accordion-header-state', JSON.stringify({
    headerClassList: Array.from(closest.classList),
    siblingClassList: Array.from(closest.nextElementSibling.classList),
  }));
});

// Retrieve the state from local storage after page refresh
const savedState = JSON.parse(localStorage.getItem('accordion-header-state'));
if (savedState) {
  const header = document.querySelector('.accordion-header');
  const sibling = header.nextElementSibling;

  header.classList.add(...savedState.headerClassList);
  sibling.classList.add(...savedState.siblingClassList);
}

相关问题