2 回答
TA贡献1869条经验 获得超4个赞
您应该能够使用 sessionStorage 而不是 localStorage 来管理它。有关此处差异的更多信息:https ://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
TA贡献1735条经验 获得超5个赞
只需将内容 localstorage 更改为 sessionStorage。以下是此问题的更新代码和解决方案(如何为当前打开的选项卡实现本地存储?)。答案是:
<script>
// Avoid scoping issues by encapsulating code inside anonymous function
(function() {
// variable to store our current state
var cbstate;
// bind to the onload event
window.addEventListener('load', function() {
// Get the current state from localstorage
// State is stored as a JSON string
cbstate = JSON.parse(sessionStorage['CBState'] || '{}');
// Loop through state array and restore checked
// state for matching elements
for(var i in cbstate) {
var el = document.querySelector('input[name="' + i + '"]');
if (el) el.checked = true;
}
// Get all checkboxes that you want to monitor state for
var cb = document.getElementsByClassName('save-cb-state');
// Loop through results and ...
for(var i = 0; i < cb.length; i++) {
//bind click event handler
cb[i].addEventListener('click', function(evt) {
// If checkboxe is checked then save to state
if (this.checked) {
cbstate[this.name] = true;
}
// Else remove from state
else if (cbstate[this.name]) {
delete cbstate[this.name];
}
// Persist state
sessionStorage.CBState = JSON.stringify(cbstate);
});
}
});
})();
</script>
特别感谢@Jacob Nelson
添加回答
举报