我尝试获得5个输入,最后输出总和。我不知道如何等待事件(onclick
)的问题,尤其是没有settimeout
时间函数或其他时间函数时。
这是代码:
var sum = 0;
var input = document.getElementById("input");
document.getElementById("submit").onclick = function(e) {
e.preventDefault();
for (var i = 0; i < 5; i++) {
sum += parseInt(input.value);
input.value = "";
//wait until the user submit another value
}
}
document.getElementById("answer").innerHTML = sum;
<form>
<input type="text" id="input">
<input type="submit" id="submit">
</form>
<p id="answer">answer</p>
<script src="script.js"></script>
因为您每次都依赖于用户按下按钮,所以不应首先使用循环。只需使用一个计数器来跟踪该功能已运行了多少次,以及何时达到所需的数量,就可以防止该功能进行更多的添加。
您还需要确保在函数内而不是在函数外更新总数。
笔记:
由于您不在任何地方提交任何数据,因此不应使用form
或submit
按钮。一个普通的button
就是你想要的。
使用.addEventListener()
而非事件属性(如)设置事件onclick
。
.innerHTML
如果字符串中没有HTML,请不要使用,.textContent
而应使用。
var sum = 0;
var count = 0;
var input = document.getElementById("input");
var answer = document.getElementById("answer");
var total = document.getElementById("total");
total.addEventListener("click", function (e) {
count++; // Increase the counter
// Check to see if we've reached the count
if(count >= 5){
this.disabled = "disabled";
input.value="";
answer.textContent = "The final total is: " + sum;
return; // Exit the function
}
sum+=parseInt(input.value);
input.value="";
answer.textContent = sum;
alert("Enter the next number and press the button.");
});
<input type="text" id="input">
<input type="button" id="total" value="Add to Total">
<p id="answer"></p>
<script src="script.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句