我想做一个复选框输入,当我们选择它时,它会得到第一个输入的数量,并将其减少10,当我们取消选择它时,第一个输入的原始数量会打印出来。例如
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onclick="one()">
<p id="par">hrllo</p>
<script>
function one () {
let input = document.getElementById("input").value;
y = input - 10;
document.getElementById("par").innerHTML = y;
if(!event.target.checked){
document.getElementById("par").innerHTML = input;
}
}
</script>
</body>
</html>
发布于 2020-04-05 03:20:41
您可以定义checkbox元素的id,并根据id检查是否选中了checkbox。
这是您更新的代码。
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
</script>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onclick="one()" id="checkboxId">
<p id="par">hrllo</p>
<script>
function one () {
var check = document.getElementById("checkboxId");
if (check.checked) {
alert("CheckBox checked.");
let input = document.getElementById("input").value;
y = input - 10;
document.getElementById("par").innerHTML = y;
} else {
alert("CheckBox not checked."+document.getElementById("input").value);
document.getElementById("par").innerHTML=document.getElementById("input").value;
}
}
</script>
</body>
</html>发布于 2020-04-05 03:01:24
您可以检查事件对象以找到checkbox的值。根据复选框值,您可以添加或减去输入元素的值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onChange="one(event)">
<p id="par">hrllo</p>
<script>
function one(event) {
let input = document.getElementById("input").value;
y = event.target.checked ? input - 10 : input;
document.getElementById("par").innerHTML = y;
}
</script>
</body>
</html>
https://stackoverflow.com/questions/61033189
复制相似问题