gpt4 book ai didi

javascript - 通过点击从 HTMLCollection 获取索引

转载 作者:行者123 更新时间:2023-12-02 23:54:58 25 4
gpt4 key购买 nike

在 HTML 中我有 9 <div> s 类为“.square”。

我想让它们可点击,我想知道点击了多少次和哪一个并将其存储到数组中。

所以,如果我点击第五个 <div>应点击 5 次[0,0,0,0,0,5,0,0,0]

    var button = document.getElementsByClassName("square");
var clicked = [0,0,0,0,0,0,0,0,0];

for (var i = 0; i < button.length; i++) {
button[i].addEventListener("click", function () {});
;}

picture

最佳答案

您可以使用语句 let 对索引/变量 i 进行 block 作用域。

var button = document.getElementsByClassName("square");
var clicked = [0, 0, 0, 0, 0, 0, 0, 0, 0];

for (let i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
clicked[i] += 1;

console.log(clicked);
});
}
<div class='square'>  [0] Click on me!</div><div class='square'>[1] Click on me!</div><div class='square'>[2] Click on me!</div><div class='square'>[3] Click on me!</div><div class='square'>[4] Click on me!</div><div class='square'>[5] Click on me!</div><div class='square'>[6] Click on me!</div><div class='square'>[7] Click on me!</div><div class='square'>[8] Click on me!</div>

关于javascript - 通过点击从 HTMLCollection 获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55444848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com