简体   繁体   中英

Why is my for loop on JavaScript and DOM manipulation making my website crash?

Hi I am a newbie in javascript and DOM manipulation...so I tried doing this to select various buttons and make them give an alert when someone clicks on them.

HTML:

<body>

<h1 id="title">Drum 🥁 Kit</h1>
<div class="set">
<button class="w drum">w</button>
<button class="a drum">a</button>
<button class="s drum">s</button>
<button class="d drum">d</button>
<button class="j drum">j</button>
<button class="k drum">k</button>
<button class="l drum">l</button>
</div>

<script src="index.js" charset="utf-8"></script>

<footer>
</footer>
</body>

JavaScript:

for (var i = 0; i = 6; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function() {
alert("I got clicked!");
});
}

When my JavaScript is the following, I am able to click the first button and get the alert, so there is no problem in my link or general format:

document.querySelectorAll("button")[0].addEventListener("click", function() {
alert("I got clicked!");
};
for (var i = 0; i < 6; i++) {
  document.querySelectorAll("button")[i].addEventListener("click", function () {
    alert("I got clicked!");
  });
}

Copy Above code and it will work. Mistakenly you wrote var i = 0; i = 6; i++ var i = 0; i = 6; i++

You are using assignment operation inside for loop which is wrong. The right syntax is

for(statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.

You can replace i=6 with i<6 or i<=6 like so

for (var i = 0; i <= 6; i++) {
       document.querySelectorAll("button")[i].addEventListener("click", function() {
       alert("I got clicked!");
        });
    }

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.

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