我们如何通过循环 JavaScript 来迭代地接受来自单个输入表单的输入?
How do we iteratively accept input from single input form through looping with JavaScript?
我有以下代码,我想知道我问的问题是否可以实现:
var sum = 0;
while (document.getElementById("number").value != 0) { //while the user keeps on entering >0, add to sum
sum = sum + document.getElementById("number").value;
}
document.getElementById("resultpara").value = sum;
<form>
<label for="number">Enter a number:</label>
<input type="text" name="number" id="number">
<label for="number">Result:</label>
<label for="resultpara"></label>
<p id="resultpara"></p>
</form>
您将需要一个输入事件侦听器。此外,在提交表单时,页面将刷新(将任何变量值擦除为其默认值),除非您停止提交事件的传播
var sum=0;
document.getElementById("number").addEventListener("input", function(event) {
var number = Number(event.target.value) || 0;
if (event.target.value !== 0) {
sum += number;
}
document.getElementById("resultpara").textContent = sum;
event.target.value = null;
});
<form>
<label for="number">Enter a number:</label>
<input type="text" name="number" id="number">
<label for="number">Result:</label>
<label for="resultpara"></label>
<p id="resultpara"></p>
</form>
我有以下代码,我想知道我问的问题是否可以实现:
var sum = 0;
while (document.getElementById("number").value != 0) { //while the user keeps on entering >0, add to sum
sum = sum + document.getElementById("number").value;
}
document.getElementById("resultpara").value = sum;
<form>
<label for="number">Enter a number:</label>
<input type="text" name="number" id="number">
<label for="number">Result:</label>
<label for="resultpara"></label>
<p id="resultpara"></p>
</form>
您将需要一个输入事件侦听器。此外,在提交表单时,页面将刷新(将任何变量值擦除为其默认值),除非您停止提交事件的传播
var sum=0;
document.getElementById("number").addEventListener("input", function(event) {
var number = Number(event.target.value) || 0;
if (event.target.value !== 0) {
sum += number;
}
document.getElementById("resultpara").textContent = sum;
event.target.value = null;
});
<form>
<label for="number">Enter a number:</label>
<input type="text" name="number" id="number">
<label for="number">Result:</label>
<label for="resultpara"></label>
<p id="resultpara"></p>
</form>