我对编程很陌生,但渴望学习。我正在尝试创建一个跟踪目标的应用程序(我不喜欢我找到的那些,所以我想自己制作)。无论如何,有复选框需要选中,当我稍后打开一个新选项卡时,我希望选中复选框。这是我的代码中的一小段:
<label class="container">Drink 2 liters of water
<input type="checkbox" checked="checked">
<span class="checkmark"></span>
</label>
如何使用 chrome.storage
功能来记住我点击了这个框?。感谢您的帮助!
最佳答案
在较高级别,您需要使用 chrome.storage在单击复选框或单击按钮时保存更改。
如果您想在每次单击复选框时都保存,您需要将一个监听器绑定(bind)到复选框的更改事件。然后调用 chrome.storage 保存。
document.querySelectorAll('input[type="checkbox"]').forEach(elem=>{ //Get all input checkboxes
elem.addEventListener('change',(event)=>{ //Add a change listener
const key = event.target.name; //get the name value from the input element
const value = event.target.checked; // has it been checked?
chrome.storage.local.set({[key]: value}, ()=> { //save it
console.log('Value is set to ' + value);
});
})
})
按下按钮时的保存将是类似的。您需要将点击监听器绑定(bind)到按钮,然后在回调中选择所有复选框并遍历它们以保存。
加载页面时,您需要获取所有已保存的值,并设置检查状态。
chrome.storage.local.get(['goal1','goal2'],(results)=>{ //Fetch goal1, goal2, goalN... from chrome.storage
//.get returns a keyed object you can loop over.
Object.keys(results).forEach((goal)=>{
//Set the check state of each goal.
document.querySelector(`input[name="${goal}"]`).checked = results[goal];
})
})
关于javascript - Chrome.storage 用于 "new tab"chrome 应用;记住复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023571/