[英]How to continue receiving numbers until a zero is entered and count total positive and negative numbers the user entered.in the textfield
更多细节:
程序应该接收一个数字并继续接收数字[来自用户输入],直到输入一个零。 当输入一个零时,程序应该 output 已经输入了多少个正数和多少个负数,然后停止。
到目前为止,我一次只能在文本字段中输入一个数字,并且只能 output 一个正值或负值。
HTML
<!DOCTYPE html>
<html>
<head>
<title>Exercise Two</title>
<link href="ex2.css" rel="stylesheet">
<script type="text/javascript" src="ex2.js"></script>
</head>
<body>
Enter number (Press 0 to stop)
<input type="text" id="num">
<button onclick="check()">Submit</button>
</body>
</html>
Javascript
function check(){
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
var x = parseInt(document.getElementById("num").value);
var posCount = 0;
var negCount = 0;
if (x > 0) {
posCount++;
}else{
negCount++;
}
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
}
您可以尝试将数据附加到隐藏的input
元素:
function check() { let btnClear = document.querySelector('button'); let inputs = document.querySelectorAll('input'); btnClear.addEventListener('click', () => { inputs.forEach(input => input.value = ''); }); var x = parseInt(document.getElementById("num").value); var totals = document.querySelector("#totals"); var posCount = totals.dataset.positives; var negCount = totals.dataset.negatives; if (x === 0) { alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount); totals.dataset.positives = 0; totals.dataset.negatives= 0; } else if (x > 0) { totals.dataset.positives = ++posCount; } else { totals.dataset.negatives= ++negCount; } }
<p>Enter number (Press 0 to stop)</p> <input type="text" id="num"> <input type="hidden" id="totals" data-positives='0' data-negatives='0'> <button onclick="check()">Submit</button>
更新
为此, you can create a positive and negative variable outside
,然后检查每个输入值; 如果输入的值为零,您可以调用警报 function 并打印结果。
这是工作代码:
var posCount = 0; var negCount = 0; function printOutput () { alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount); } function check(){ let btnClear = document.querySelector('button'); let inputs = document.querySelectorAll('input'); var x = parseInt(document.getElementById("num").value); document.getElementById("num").value = '' if (x > 0) { posCount++; }else if (x < 0){ negCount++; } else { printOutput(); // re-initiate value posCount = 0; negCount = 0; } }
<.DOCTYPE html> <html> <head> <title>Exercise Two</title> <link href="ex2.css" rel="stylesheet"> <script type="text/javascript" src="ex2.js"></script> </head> <body> Enter number (Press 0 to stop) <input type="text" id="num"> <button id="submit-btn" onclick="check()">Submit</button> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.