gpt4 book ai didi

javascript - 如何仅在未选中复选框时才执行函数?

转载 作者:行者123 更新时间:2023-11-30 13:48:50 25 4
gpt4 key购买 nike

我正在开发一款小型骰子游戏,用户可以在其中锁定特定的骰子。但我无法让它与 if else 语句一起使用。如何仅在未选中复选框的情况下“掷”骰子?

const btnRoll = document.querySelector('.btn_roll');

btnRoll.addEventListener('click', () => {
roll();
});

function roll() {
const dice1 = document.querySelector('.dice1');
const dice2 = document.querySelector('.dice2');
const dice3 = document.querySelector('.dice3');

if (!document.getElementById('dice-1').checked) {
randomOne = Math.floor(Math.random() * 6) + 1;
dice1.src = `img/dice-${randomOne}.png`;
console.log(!document.getElementById('dice-1').checked);
} else if (!document.getElementById('dice-2').checked) {
randomTwo = Math.floor(Math.random() * 6) + 1;
dice2.src = `img/dice-${randomTwo}.png`;
} else if (!document.getElementById('dice-3').checked) {
randomThree = Math.floor(Math.random() * 6) + 1;
dice3.src = `img/dice-${randomThree}.png`;
} else {
console.log('no checkboxes are selected');
}
}
<form id="dices">
<input type="checkbox" id="dice-1" name="dice-1" value="dice-1" />
<img src="img/dice-5.png" alt="Dice" class="dice1" id="dice-1" />
<input type="checkbox" id="dice-2" name="dice-2" value="dice-2" />
<img src="img/dice-5.png" alt="Dice" class="dice2" id="dice-2" />
<input type="checkbox" id="dice-3" name="dice-3" value="dice-3" />
<img src="img/dice-5.png" alt="Dice" class="dice3" id="dice-3" />
<input type="checkbox" id="dice-4" name="dice-4" value="dice-4" /> 5.png" alt="Dice" class="dice6" id="dice-6" />
</form>
<br />
<button class="btn_roll">roll</button>

最佳答案

您正在使用“else-if”语句,当其中一个语句运行时,它会有效地使您的逻辑短路。仅将“else-if”替换为“if”:s。

(我用一个“if”语句替换了最后一个“else”语句,它是其他 if 语句的否定,因为我们不能在这里做 else。)


function roll() {
const dice1 = document.querySelector('.dice1');
const dice2 = document.querySelector('.dice2');
const dice3 = document.querySelector('.dice3');

const firstDiceChecked = document.getElementById('dice-1').checked
const secondDiceChecked = document.getElementById('dice-2').checked
const thirdDiceChecked = document.getElementById('dice-3').checked

if (!firstDiceChecked) {
randomOne = Math.floor(Math.random() * 6) + 1;
dice1.src = `img/dice-${randomOne}.png`;
console.log(!document.getElementById('dice-1').checked);
}
if (!secondDiceChecked) {
randomTwo = Math.floor(Math.random() * 6) + 1;
dice2.src = `img/dice-${randomTwo}.png`;
}
if (!thirdDiceChecked) {
randomThree = Math.floor(Math.random() * 6) + 1;
dice3.src = `img/dice-${randomThree}.png`;
}
if (!firstDiceChecked && !secondDiceChecked && !thirdDiceChecked) {
console.log('no checkboxes are selected');
}
}

关于javascript - 如何仅在未选中复选框时才执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718824/

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