【问题标题】:How to combing HTML and JavaScripts in one [closed]如何将 HTML 和 JavaScript 合二为一 [关闭]
【发布时间】: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


    【解决方案1】:

    只需将 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>
    

    【讨论】:

      猜你喜欢
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      相关资源
      最近更新 更多