繁体   English   中英

如何将 HTML 和 JavaScript 合二为一

[英]How to combing HTML and JavaScripts in one

我如何将以下 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 放在script标签中

<label class="form-control">
  <input id="checkbox" type="checkbox" name="purchased" />
  Purchased
</label> 


<script type="text/javascript">
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;
}
</script>

暂无
暂无

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

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