【发布时间】:2022-07-30 05:28:38
【问题描述】:
我从未使用过编码,我正在尝试将以下代码嵌入到我的个人网站中。唯一的问题是,当我复制和粘贴 html 时显示为复选框和所有内容,但 JavaScript 只是在键入时出现,它没有作为实现到复选框中的特定功能出现。那么我将如何将以下 html 和 js 组合在一起,以便它们可以正常工作,最终会是什么样子?谢谢!
<label class="form-control">
<input id="checkbox" type="checkbox" name="purchased" />
Purchased
</label>
const cb = document.getElementById('checkbox');
//run every time the checkbox is set
cb.addEventListener('input', (e) => {
console.log('changed');
localStorage.setItem('purchased', e.target.checked);
});
//run once on page load, check if it is set in LS if yes then check it
const localPurchasedValue = localStorage.getItem('purchased');
if (localPurchasedValue === 'true') {
cb.checked = true;
}
【问题讨论】:
标签: javascript html combine