gpt4 book ai didi

JavaScript 警报不能与 div 标签一起正常工作

转载 作者:行者123 更新时间:2023-11-28 04:17:16 27 4
gpt4 key购买 nike

html中有16个框。

<div id="box-container">
<div class="box" data-coord="0:0" style="clear: left"></div> <div class="box" data-coord="0:1"></div> <div class="box" data-coord="0:2"></div> <div class="box" data-coord="0:3"></div>
<div class="box" data-coord="1:0" style="clear: left"></div> <div class="box" data-coord="1:1"></div> <div class="box" data-coord="1:2"></div> <div class="box" data-coord="1:3"></div>
<div class="box" data-coord="2:0" style="clear: left"></div> <div class="box" data-coord="2:1"></div> <div class="box" data-coord="2:2"></div> <div class="box" data-coord="2:3"></div>
<div class="box" data-coord="3:0" style="clear: left"></div> <div class="box" data-coord="3:1"></div> <div class="box" data-coord="3:2"></div> <div class="box" data-coord="3:3"></div>
</div>

我想编写将执行以下操作的 js 代码:
当我点击任何框时,它会提醒它的订单号从 1 到 16。
下面是我的js代码:

<script type="text/javascript">
var boxArray = document.getElementsByClassName("box");
for (var i = 0; i < boxArray.length; i++) {
boxArray[i].onclick = function () {
var say = function (i) {
alert(i);
};
say(i);
}
}
</script>

但是每次都提示16
有什么问题?
你能帮帮我吗?

最佳答案

使用经典IIFE: Immediately Invoked Function Expression你可以这样写:

var boxArray = document.getElementsByClassName("box");
for (var i = 0; i < boxArray.length; i++) {
boxArray[i].onclick = (function (i) {
return function (e) {
var say = function (i) {
alert(i);
};
say(i);
};
})(i);
}
<div id="box-container">
<div class="box" data-coord="0:0" style="clear: left">1</div> <div class="box" data-coord="0:1">2</div> <div class="box" data-coord="0:2">3</div> <div class="box" data-coord="0:3">4</div>
<div class="box" data-coord="1:0" style="clear: left">5</div> <div class="box" data-coord="1:1">6</div> <div class="box" data-coord="1:2">7</div> <div class="box" data-coord="1:3">8</div>
<div class="box" data-coord="2:0" style="clear: left">9</div> <div class="box" data-coord="2:1">10</div> <div class="box" data-coord="2:2">11</div> <div class="box" data-coord="2:3">12</div>
<div class="box" data-coord="3:0" style="clear: left">13</div> <div class="box" data-coord="3:1">14</div> <div class="box" data-coord="3:2">15</div> <div class="box" data-coord="3:3">16</div>
</div>

关于JavaScript 警报不能与 div 标签一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40225647/

27 4 0