繁体   English   中英

在浏览器的localStorage中存储活动的class数据

[英]Storing the active class data in localStorage of browser

当我导航到其他页面时,我正在尝试将单击的链接的活动 class 存储在 localStorage 中。 怎么做?

 <div id="collapse2" class="panel-collapse collapse"> <ul class="list-group"> <li class="list-group-item active" style="background-color: #394263; color: white"><a id="a" style="color: white">A</a></li> <li class="list-group-item" style="background-color: #394263; color: white"><a id="p" style="color: white">P</a></li> <li class="list-group-item" style="background-color: #394263; color: white"><a id="s" style="color: white">S</a></li> </ul> </div>

为每个列表创建一个 id..

<body onload = "check_storage()">
<div id="collapse2" class="panel-collapse collapse">
<ul class="list-group">
  <li class="list-group-item active" id="id1" onclick= "active("id1")"><a id="a" style="color: white">A</a</li>
  <li class="list-group-item" id = "id2" onclick = "active("id2")"><a id="p" style="color: white">P</a></li>
  <li class="list-group-item" id = "id3" onclick = "active("id3")"><a id="s" style="color: white">S</a></li>
</ul>
</div>

在 JavaScript 创建函数以将 id 存储在 localstorage

//onload of your page this will get called
 function check_storage() {
    //check if there is any value in localStorage
if (localStorage.getItem("listId") != null) {
    //get that value
    var val= localStorage.getItem("listId");
    console.log(val);
    setActive(val); //call function
     }
     }

 function active(id) {
localStorage.removeItem('listId');//clear previous data
localStorage.setItem("listId", id);//add data to storage
console.log(id);
      }

 function setActive(value) {
document.getElementById(value).classList.value = "list-group-item active";
    }

在加载页面正文时,它会检查 localstorage 中的 id 并将该 id 设为活动组。 在调用活动 function 时,它会清除之前存储的数据并将当前 id 添加到本地存储。

假设每个a都有一个id ,您可以使用Storage.setItem设置它:

localStorage.setItem(
  'activeListGroupItem',
  $('#collapse2 .list-group-item.active a').attr('id')
);

然后你可以得到它并使用Storage.getItem应用它:

$('#' + localStorage.getItem('activeListGroupItem'))
  .parent().addClass('active');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM