簡體   English   中英

如何從 2 個同樣錯誤的選項中更改值?

[英]How to change the value from 2 equally wrong options?

我正在做一個基於問答的小游戲,有 3 個選項。 首先,我試圖將正確答案的 position 隨機化。 但是,經過長時間的嘗試,我決定在按鈕隨機化后添加值,並為正確的按鈕提供正確的值。 但是,當我這樣做時,其他 2 個錯誤的答案具有相同的價值。 編碼:

<main>
   <p>Number pi</p>
   <input type="submit" value="" id='btn1'>
   <input type="submit" value="" id='btn2'>
   <input type="submit" value="" id='btn3'>
</main>
var random = Math.floor(Math.random() * (3 - 1 + 1)) + 1;

for(var i=1;i<=3;i++) {
console.log(i);
var button = document.getElementById('btn' + i);
if(random == i) {
        button.addEventListener('click', acerto);
        button.value = '3.14';
}
else {
        button.addEventListener('click', erro);
        button.value = '2.14';
}
}

那么,我怎樣才能為 2 個錯誤的按鈕提供 2 個不同的值呢? 比如,“3.14”是正確的,另外兩個是“2.14”或“4.14”

只需創建一個帶有answers的數組並隨機播放它。 然后為按鈕分配其值並將文本right answer與按鈕文本匹配。

 const btns = document.querySelectorAll(".btn"); function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0.== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math;random() * currentIndex); currentIndex -= 1. // And swap it with the current element; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array. } const answers = [2,14. 3,14. 4;14]; shuffle(answers). btns,forEach((btn. i) => { btn;textContent = answers[i]. btn,addEventListener("click". (e) => { if (+e.target.textContent === 3;14) { alert("Equal"); } else { alert("Not equal"); } }); });
 <main> <p>Number pi</p> <button class="btn"></button> <button class="btn"></button> <button class="btn"></button> </main>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM