javascript - 如何使用 JavaScript 在两个值之间使用复选框动态更改 innerHTML?
问题描述
我在这里有点难过。我使用的是纯 JavaScript,没有 jQuery。
I want to change the innerHTML of a heading between two values when a checkbox is selected. 当复选框被选中时,我让它工作,但取消选中复选框不会将其切换回来。
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。
解决方案
使用复选框的选中属性来确定它是否被选中
这是更新的小提琴: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>
推荐阅读
- python - 如何在 python 的每一行中打印 4 个数字?
- flutter - syncfusion_flutter_charts 没有提供我所有的数据
- swift - Swift Firebase Firestore 用户列表(读取次数过多)
- python - 字典键()集合操作记录在哪里?
- mysql - 连接到 MySQL 并执行查询的最佳方式?(可能与 Dapper)
- javascript - 从嵌套依赖项导入纱线
- github - macOS Catalina 上的 Home brew 安装失败
- embedded-linux - 如何监控 Linux 中所有进程的内存使用情况?
- python-3.x - tkinter PhotoImage 仍然不适用于某些 PNG 文件
- c# - 为什么我应该始终为我的 Authorize 属性定义 JwtBearerDefaults.AuthenticationScheme?