javascript - 多个复选框动作
问题描述
我想制作多个复选框,每次我检查其中一个复选框时,第一个输入的值都会减少一个数字,例如,当我们选择 checkbox1 时,输入中的数字减少 10,当我们选择 checkbox2 时,它减少 20,当我们选择它们都减少了 30。不过,我已经处理了第一个复选框。
<html lang="en">
<head>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onclick="one()" id="checkboxId">
<input type="checkbox" onclick="" id="checkboxId2">
<p id="par">hello</p>
<script>
function one () {
var check = document.getElementById("checkboxId");
if (check.checked) {
let input = document.getElementById("input").value;
y = input - 10;
document.getElementById("par").innerHTML = y;
} else {
document.getElementById("par").innerHTML=document.getElementById("input").value;
}
}
</script>
</body>
</html>
解决方案
您可以尝试使用data-*属性。此外,您只能从选中的复选框中获取值,将它们相加并从输入值中扣除。
试试下面的方法:
function one () {
var total = Array.from(document.querySelectorAll(':checked'))
.map(el => el.getAttribute('data-value'))
.reduce((a,c) => a+ Number(c), 0);
document.getElementById("par").textContent = Number(document.getElementById("input").value) - total;
}
<input type="number" id="input">
<input type="checkbox" onclick="one()" data-value="10" id="checkboxId">
<input type="checkbox" onclick="one()" data-value="20" id="checkboxId2">
<p id="par">hello</p>
推荐阅读
- arrays - C中的“终止”数组
- rundeck - Rundeck - 在脚本中获取执行作业的用户名
- parsing - Antlr4 有没有办法在带有监听器的节点上行走
- swift - pod 'FBSDKLoginKit' 不会安装在 Xcode 项目中
- oracle - Oracle子查询同时使用count和max与join
- node.js - Nodejs 加密的最短哈希是多少
- c++ - C++ 是否可以保证模板生成的文字条件将被优化掉?
- ruby-on-rails - 从 jQuery ruby on rails 渲染部分
- c++ - 如何比较 C++ 中的字符串以便按字典顺序对它们进行排序?
- python - 将字符串拆分为两个整数,python