首页 > 解决方案 > 如何使用 JavaScript 在两个值之间使用复选框动态更改 innerHTML?

问题描述

我在这里有点难过。我使用的是纯 JavaScript,没有 jQuery。

I want to change the innerHTML of a heading between two values when a checkbox is selected. 当复选框被选中时,我让它工作,但取消选中复选框不会将其切换回来。

JSFiddle!

HTML

<h2 id="billing-information-header"></h2>

<p id="before-billing">Please enter your billing information below. Shipping to a different address? Check the box below the billing fields.</p>

<h2>SHIPPING INFORMATION:</h2>

<input id="ship-to-different-address-checkbox" type="checkbox" name="ship_to_different_address"><span>Ship to a Different Address?</span>

JS

window.addEventListener('load', function() {
        const checkBox = document.querySelector('#ship-to-different-address-checkbox');
        const heading = document.querySelector('#billing-information-header');
        const message = document.querySelector('#before-billing');

        heading.innerHTML = 'BILLING & SHIPPING INFORMATION:';

        checkBox.addEventListener('click', function() {
            heading.innerHTML = 'BILLING INFORMATION:';
        });

});

我计划heading在取消选中该框后切换回“BILLING & SHIPPING INFORMATION”。我还计划动态更改message内部 HTML。

标签: javascripthtmlwoocommerce

解决方案


使用复选框的选中属性来确定它是否被选中

这是更新的小提琴:https ://jsfiddle.net/978ucdgt/

window.addEventListener('load', function() {
  const checkBox = document.querySelector('#ship-to-different-address-checkbox');
  const heading = document.querySelector('#billing-information-header');
  const message = document.querySelector('#before-billing');

  heading.innerHTML = 'BILLING & SHIPPING INFORMATION:';

  checkBox.addEventListener('click', (e) => {
    heading.innerHTML = e.target.checked ? 'BILLING INFORMATION:' : 'BILLING & SHIPPING INFORMATION:'

  });

});
<h2 id="billing-information-header"></h2>

<p id="before-billing">Please enter your billing information below. Shipping to a different address? Check the box below the billing fields.</p>

<h2>SHIPPING INFORMATION:</h2>

<input id="ship-to-different-address-checkbox" type="checkbox" name="ship_to_different_address"><span>Ship to a Different Address?</span>


推荐阅读