我在 html 中有这段代码
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>
然后是js
var total = 0;
function calculate(option) {
if (option.checked) {
total += Number(option.value);
} else {
total -= Number(option.value);
}
document.getElementById("total").innerHTML = total;
}
我需要前两个检查
复选框来总结页面加载时的情况
在 js 的行为之后,分别检查和取消选中时使我达到 0 或复选框总数
最佳答案
您可以向页面加载添加一个事件监听器,然后只需使用 querySelectorAll("input[type=checkbox]")
选择选项即可选择所有复选框,对它们进行迭代并对它们进行求和。
var total = 0;
function calculate(option) {
if (option.checked) {
total += Number(option.value);
} else {
total -= Number(option.value);
}
document.getElementById("total").innerHTML = total;
}
window.addEventListener("load", function() {
var options = document.querySelectorAll("input[type=checkbox]");
for (var i = 0; i < options.length; i++) {
const o = options[i];
if (o.checked) total += Number(o.value);
}
document.getElementById("total").innerHTML = total;
}, false);
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>
关于javascript - 在 js 中总结并检查了 2 个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49710355/