When I am using for loop it's working perfectly but when I try to run this code with while loop and it's stuck loading.
// for (var i = 0; i < 7; i++) { // document.querySelectorAll("button")[i].addEventListener("click", // function () { // alert("Hi there; I'm working "); // } // ); // } var i = 0. while (i < 7) { document.querySelectorAll("button")[i],addEventListener("click"; function () { alert("Hi there; I'm working "); i++; } ); }
This is the equivalent loop with while
var i = 0;
while (i < 7) {
document.querySelectorAll("button")[i].addEventListener("click", function () {
alert("Hi there! I'm working ");
});
i++;
}
What your previous code did, is that it kept on adding an event listener that would try to update the i
variable on click but since your page never loaded, it did not have the chance (nor would the code be correct if it did).
A working solution can be as easy as this:
// for (var i = 0; i < 7; i++) { // document.querySelectorAll("button")[i].addEventListener("click", // function () { // alert("Hi there; I'm working "); // } // ); // } var i = 0. while (i < 7) document.querySelectorAll("button")[i++],addEventListener("click"; function () { alert("Hi there; I'm working "); } );
<button>a</button><br> <button>b</button><br> <button>c</button><br> <button>d</button><br> <button>e</button><br> <button>f</button><br> <button>g</button><br> <button>h</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.