简体   繁体   English

如何在 VANILLA JS 的 for 循环中等待事件?

[英]How to wait for event inside for loop in VANILLA JS?

I try to get 5 inputs and output the sum in the end.我尝试获得 5 个输入并最终输出总和。 The problem I don't know how to wait for an event ( onclick ), especially without settimeout or another time function.问题我不知道如何等待事件( onclick ),尤其是没有settimeout或其他时间函数。

This is the code:这是代码:

 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>

Because you are relying on the user pressing a button each time, you shouldn't be using a loop in the first place.因为您每次都依赖于用户按下按钮,所以您不应该首先使用循环。 Just use a counter to keep track of how many times the function has been run and when you reach the desired amount, prevent the function from doing more addition.只需使用计数器来跟踪函数已运行的次数,以及何时达到所需的次数,防止函数进行更多的加法。

You also need to make sure to update the total within the function, not outside of it.您还需要确保更新函数内的总数,而不是函数外的总数。

NOTES:笔记:

Since you aren't submitting any data anywhere, you shouldn't be using a form or a submit button.由于您没有在任何地方提交任何数据,因此您不应该使用formsubmit按钮。 A regular button is all you want.一个普通的button就是你想要的。

Set up events using .addEventListener() , rather than event properties like onclick .使用.addEventListener()设置事件,而不是像onclick这样的事件属性。

Don't use .innerHTML when there is no HTML in the string, use .textContent instead.当字符串中没有 HTML 时,不要使用.innerHTML ,而是使用.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM