gpt4 book ai didi

Javascript 数组将元素随机化到选定元素

转载 作者:行者123 更新时间:2023-12-01 03:50:50 25 4
gpt4 key购买 nike

我正在尝试创建一个函数,当您单击其中一个骰子元素时,它将重新滚动该骰子,并且它左侧的每个元素也会重新滚动。

目前,当您加载页面时,骰子编号为 1-6,当您单击骰子时,它会重新掷骰子。我在尝试弄清楚如何使所选元素左侧的所有元素发生变化时遇到了一些麻烦。

这是我所拥有的。

   (function () {
var dieElements;

dieElements = Array.prototype.slice.call(document.querySelectorAll('#dice div'));

dieElements.forEach(function (dieElement, whichDie) {

dieElement.textContent = whichDie + 1;

dieElement.addEventListener('click', function () {
dieElement.textContent = Math.floor(Math.random() * 6) + 1;
}, false);
});
}());

这是 html

<fieldset id="dice-area">
<legend>Dice</legend>
<div class="box-of-dice" id="dice">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</fieldset>

最佳答案

您已经获得了单击的骰子的索引以及被困在闭包中的所有骰子的数组。您所需要的只是像这样使用它们(轻松):

(function() {
var dieElements;

dieElements = Array.prototype.slice.call(document.querySelectorAll('#dice div'));

dieElements.forEach(function(dieElement, whichDie) {
dieElement.textContent = whichDie + 1;

dieElement.addEventListener('click', function() { // when this die is clicked
for(var i = 0; i <= whichDie; i++) // loop over all the elements in dieElements array from index 0 to index whichDie (included)
dieElements[i].textContent = Math.floor(Math.random() * 6) + 1; // change their textContent
}, false);
});
}());
#dice div {
display: inline-block;
border: 1px solid black;
padding: 5px;
margin: 5px;
width: 30px;
height: 30px;
text-align: center;
cursor: pointer;
}
<div id="dice">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>

关于Javascript 数组将元素随机化到选定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43219380/

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