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
添加回答
舉報