试用JavaScipt语言设计一个程序:自动计算出选中的checkbox项的合计金额值并显示出来。
HTML代码:
<label><input type="checkbox" name="item" value="10.00"> Item 1 ($10.00)</label>
<label><input type="checkbox" name="item" value="20.00"> Item 2 ($20.00)</label>
<label><input type="checkbox" name="item" value="30.00"> Item 3 ($30.00)</label>
<label><input type="checkbox" name="item" value="40.00"> Item 4 ($40.00)</label>
<p>Total: $<span id="total">0.00</span></p>
JavaScript代码:
const checkboxes = document.querySelectorAll('input[type=checkbox][name=item]');
const total = document.getElementById('total');
function getTotal() {
let sum = 0;
checkboxes.forEach((checkbox) => {
if (checkbox.checked) {
sum += parseFloat(checkbox.value);
}
});
return sum.toFixed(2);
}
checkboxes.forEach((checkbox) => {
checkbox.addEventListener('change', () => {
total.textContent = getTotal();
});
});
说明:
- 首先使用
querySelectorAll方法获取所有名称为item的复选框元素,并使用getElementById方法获取显示总额的元素。 - 定义一个
getTotal函数,用于计算选中的复选框的总金额。在函数中,使用forEach方法遍历所有复选框元素,如果元素被选中,则将其value属性解析为浮点数并加入总金额中。最后使用toFixed方法将总金额保留两位小数后返回。 - 在每个复选框元素上添加
change事件监听器,当复选框状态发生变化时,更新显示总额的元素的文本内容为调用getTotal函数的返回值
原文地址: https://www.cveoy.top/t/topic/cZrh 著作权归作者所有。请勿转载和采集!