我正在尝试创建一个函数,当您单击其中一个骰子元素时,它将重新掷骰子,并且它左侧的每个元素也会重新掷骰子。
目前,当您加载页面时,我有它,骰子编号为 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>