【发布时间】:2020-09-28 18:14:55
【问题描述】:
我很难理解为什么我的代码只运行一次。我可以单击出现的第一个方块并更改班级,但它似乎停在那里。我试图能够单击方块并出现新的方块等等。我无法单击创建的第二个正方形。我已经记录了“totalSquares.length”和“i”。 “i”似乎小于 totalSquares 的长度,所以我不确定为什么我的循环会停止。我还有一个 Codepen 链接 here。先感谢您。如果您需要更多说明,请告诉我。
HTML:
<body>
<h1>Test
<br>
Your
<br>
Aim
</h1>
<p>Score: </p><span id="score">0</span>
<div id="container">
<div id="square"></div>
</div>
<script src="script.js"></script>
</body>
JS:
let totalSquares = [];
const squares = document.getElementById("square");
const totalScore = document.getElementById("score");
const heading = document.querySelector("h1");
let score = 0;
totalSquares.push(squares);
for (var i = 0; i < totalSquares.length; i++) {
totalSquares[i].addEventListener("click", function() {
createSquare();
this.classList.add("clicked");
score++;
totalScore.innerHTML = score;
console.log(totalSquares.length, i);
});
}
function createSquare() {
let div = document.createElement('div');
div.setAttribute("id", "square");
document.getElementById("container").appendChild(div);
totalSquares.push(div);
}
【问题讨论】:
-
你的循环只运行一次。
createSquare中没有任何内容告诉它将事件侦听器添加到新方块。
标签: javascript for-loop iterator