我正在尝试创建一个类似“谁想成为百万富翁?”的测验。问题是随机数和随机操作(+,-,*,//)。用户有4个提供的答案-我放置了4个不同值的按钮。现在,我遇到了一个小问题--如何创建一个变量来获取用户单击的按钮的值。我将创建一个"while“循环,它将进行随机数和随机操作,只要该变量等于结果,它就会工作。我的问题是我不知道哪个按钮被点击了。
<div class="row">
<div class="d-flex justify-content-center">
<div class="col-5 col-md-5 col-lg-5 my-pola">
<button id="first">1</button>
</div>
<div class="col-5 col-md-5 col-lg-5 my-pola">
<button id="second">2</button>
</div>
</div>
<div class="row">
<div class="d-flex justify-content-center">
<div class="col-5 col-md-5 col-lg-5 my-pola">
<button id="third">3</button>
</div>
<div class="col-5 col-md-5 col-lg-5 my-pola">
<button id="fourth">4</button>
</div>
</div>发布于 2021-01-18 09:18:39
您描述的行为可能与input[type="radio"]或input[type="button"]的input element更匹配。
无线电输入
如果玩家在回答之前会检查他们的选择,请考虑radio inputs。这里的权衡是编写验证代码来检查玩家是否选择了答案:
function alertAnswer() {
/* The important part of this query selector is the `:checked` pseudo-class identifying the player's choice. The root of the selector could be however your selector your input elements, here I've used tag and name attribute for demo purposes only. */
const choice = document.querySelector('input[name="choice"]:checked');
if (!choice) {
alert('Please choose your answer.');
}
else {
alert(choice.value);
}
}<p class="question">What is one plus one?</p>
<label>
<input name="choice" type="radio" value="1">
1
</label>
<label>
<input name="choice" type="radio" value="2">
2
</label>
<label>
<input name="choice" type="radio" value="3">
3
</label>
<label>
<input name="choice" type="radio" value="4">
4
</label>
<button type="submit" onclick="alertAnswer()">Answer</button>
按钮输入
如果玩家像你在问题中描述的那样,在他们选择后立即提交他们的选择,请考虑input buttons。在语义上,输入和按钮之间的重要区别是我们的选择元素有一个value属性,这使得使用它来提交答案变得更简单。这里的权衡是输入值必须与显示值相同。
<p class="question">What is one plus one?</p>
<input type="button" value="1" onclick="alert(value)">
<input type="button" value="2" onclick="alert(value)">
<input type="button" value="3" onclick="alert(value)">
<input type="button" value="4" onclick="alert(value)">
https://stackoverflow.com/questions/65767120
复制相似问题