【发布时间】:2021-09-15 08:29:59
【问题描述】:
当我点击骰子时,我需要改变骰子的 this.value,但现在我只是想让它显示警报,但我什至做不到。我已经深入研究了 e.target 以及几乎所有我能找到的东西,但我只是不知道我错过了什么我觉得这是一个愚蠢的问题,但我现在花了一个多小时试图弄清楚这一点出来了,我拿不到。
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
const diceArray = [];
const body = document.body;
class Die {
constructor() {
this.value = this.roll();
this.div = $(`<div class="a-die d-flex align-items-center justify-content-center"><h1 class="die-text">${this.value}</h1></div>`);
diceArray.push(this);
$('#diceHolder').append(this.div);
this.div.addEventListener("click", function() {
alert('hello');
})
}
roll = () => {
return randomNumber(1, 7);
}
refreshView = () => {
$(this.div).find('h1').text(this.value);
}
rollAll = () => {
$(this.value).replaceWith(randomNumber(1, 7));
}
}
$('#genDice').on('click', () => {
let thisDie = new Die()
});
$('#yahtzee').on('click', () => $('.die-text').text(randomNumber(1, 7)));
$('#sumDice').on('click', () => {
const thing = diceArray.reduce((acc, val) => {
return acc + val.value;
}, 0)
alert(thing);
})
$('#rollDice').on('click', () => diceArray.forEach(val => {
// console.log(val);
val.value = randomNumber(1, 7);
val.refreshView();
}));
$('#remove').on('click', () => {
$('.a-die').remove()
$(diceArray).empty();
});
console.log(diceArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex justify-content-around mb-5 mt-2 py-3 bg-light" style="border: 1px solid black;">
<div id="genDice" class="btn btn-primary">Generate Die</div>
<div id="rollDice" class="btn btn-secondary">Roll All Die</div>
<div id="sumDice" class="btn btn-success">Sum All Dice</div>
<div id="yahtzee" class="btn btn-danger">Yahtzee</div>
<div id="remove" class="btn btn-dark">Bye-Bye</div>
</div>
<div id="diceHolder" class="d-flex justify-content-evenly"></div>
【问题讨论】:
标签: javascript jquery oop ecmascript-6