我正在尝试将所选单选按钮值与预定值进行比较,然后显示与匹配或不匹配相对应的文本。这似乎应该足够简单,但它显示“匹配”文本,无论这两个值是否匹配。
这是我的代码:
submit: function() {
$("#submit").click(function(){
if($("input:radio[name=answers]:checked").val() == triviaGame.correctSelection) {
$("#result").text("Correct!");
} else {$("#result").text("I'm sorry, you did not select the correct answer :(");}
});
我也试过了:
submit: function() {
$("#submit").click(function() {
if ($("input:radio[name=answers]:checked").val() == triviaGame.questions[questionSelectNum].choices[triviaGame.questions[questionSelectNum].choices[0]]) {
$("#result").text("Correct!");
} else {$("#result").text("I'm sorry, you did not select the correct answer :(");}
});
我已尝试===
和==
以及其他语法调整。
我检查确保我在nextQuestion
方法中正确设置了单选按钮的值,并且我的测试工作正常,所以我不认为这是问题所在。最让我困惑的是if(true)代码在不应该执行而不执行else(false)代码时执行,而不应该执行,我认为这可能是一个更有可能的错误。
这是我的HTML:
<div>
<button id = "nextQuestion">Next Question</button>
<br></br>
<div id = "questionDisplay"></div>
<br></br>
<input type="radio" id= "1" name="answers" value="defaultVal">
<label id= "labelOne">Answer 1</label>
<br></br>
<input type="radio" id= "2" name="answers" value="defaultVal">
<label id= "labelTwo">Answer 2</label>
<br></br>
<input type="radio" id= "3" name="answers" value="defaultVal">
<label id= "labelThree">Answer 3</label>
<br></br>
<input type="radio" id= "4" name="answers" value="defaultVal">
<label id= "labelFour">Answer 4</label>
<br></br>
<button id = "submit">Submit</button>
<br></br>
<div id= "result">Please select an answer above</div>
</div>
Here's指向jsbin完整代码的链接。
答案 0 :(得分:0)
道歉,我最初得到了错误的结局,我认为你只需要更新这一部分:
//sets the values of each radio button to the same value as each radio's corresponding answer
$("#1") .val(triviaGame.firstAnswer);
$("#2") .val(triviaGame.firstAnswer);
$("#3") .val(triviaGame.firstAnswer);
$("#4") .val(triviaGame.firstAnswer);
有了这个:
//sets the values of each radio button to the same value as each radio's corresponding answer
$("#1") .val(triviaGame.firstAnswer);
$("#2") .val(triviaGame.secondAnswer);
$("#3") .val(triviaGame.thirdAnswer);
$("#4") .val(triviaGame.fourthAnswer);