为什么点击的按钮不是赢家,即使它的id与中奖号码匹配



我想创建三个按钮,其中只有一个应该是赢家。当我点击获胜者按钮时,输出将是"祝贺您已找到获胜按钮";如果点击的按钮不是获胜的按钮继续尝试";

获胜者按钮将是id将与1到3之间随机选择的值匹配的按钮。这个值将在函数"0"内产生WinnerButton(buttonCnt(";借助于方法">数学随机数(("。

<p>Which button is the winner ?</p>
<button type = "submit" id = "1" onclick = "handleClick(this.id)"></button>
<button type = "submit" id = "2" onclick = "handleClick(this.id)"></button>
<button type = "submit" id = "3" onclick = "handleClick(this.id)"></button>
<pre id = "output"></pre>
<script>
let buttonCnt = 3;

const output = document.querySelector('#output');
function WinnerButton(buttonCnt) {
let Winner = Math.ceil(Math.random() * buttonCnt);
return Winner;
}

function handleClick(clicked_id) {
if (Number(clicked_id) === WinnerButton(buttonCnt)) {
output.textContent = "Congratulations. You have found the winner button!"
} else {
output.textContent = "Keep trying."
}
}
</script>

问题是,如果我在控制台中选中获胜者按钮并单击它,在某些情况下,单击的按钮不是获胜者。如果你点击下面的图片,你会看到,即使控制台上说中奖按钮是3号,我也会收到消息";继续尝试";如果我点击它。我知道你没有看到我点击了第三个按钮,但你可以相信我做到了。

我不明白为什么会发生这种事。你能给我解释一下吗?我不想要一个直接的解决方案,而是想要一个关于我做错了什么的解释。

非常感谢。

上述示例的屏幕拍摄

您应该只使用一次函数WinnerButton,因为如果您在handleClick中使用它,它每次都会更改获胜者id。

let buttonCnt = 3;
let winnerId = WinnerButton(buttonCnt)
const output = document.querySelector('#output');
function WinnerButton(buttonCnt) {
let Winner = Math.ceil(Math.random() * buttonCnt);
return Winner;
}
function handleClick(clicked_id) {
if (Number(clicked_id) === winnerId) {
output.textContent = "Congratulations. You have found the winner button!"
} else {
output.textContent = "Keep trying."
}
}
<p>Which button is the winner ?</p>
<button type = "submit" id = "1" onclick = "handleClick(this.id)">1</button>
<button type = "submit" id = "2" onclick = "handleClick(this.id)">2</button>
<button type = "submit" id = "3" onclick = "handleClick(this.id)">3</button>
<pre id = "output"></pre>

如果每次都生成结果,那么每次单击按钮都会生成一个新值。我从函数中取出了随机数的生成。

我计算了一下按钮的数量,这样以后你就可以在游戏中添加更多的按钮了。

const buttonCnt = document.querySelectorAll("button").length;
const output = document.querySelector('#output');
const result = Math.ceil(Math.random() * buttonCnt);
function handleClick(clicked_id) {
output.textContent = +clicked_id === result ? "Congratulations. You have found the winner button!" : "Keep trying."
}
<p>Which button is the winner ?</p>
<button type="submit" id="1" onclick="handleClick(this.id)">1</button>
<button type="submit" id="2" onclick="handleClick(this.id)">2</button>
<button type="submit" id="3" onclick="handleClick(this.id)">3</button>
<pre id = "output"></pre>

最新更新