[英]True Or False validation with jquery
我正在嘗試制作一個正確或錯誤的游戲,需要幫助編寫該函數來驗證用戶是對還是錯。 我的DOM結構如下:
<ul class="multiplechoice_answergroup">
<li class="multiplechoice_answer True">
<input class="checkbox" type="checkbox" name="checkme">
<p>This answer is true</p>
</li>
<li class="multiplechoice_answer False">
<input class="checkbox" type="checkbox" name="checkme">
<p>This answer is false</p>
</li>
</ul>
這是我嘗試過的jQuery,但我不斷得到答案是正確的:
truefalseSubmit = function() {
if($('.multiplechoice_answergroup').children('li').hasClass('False') && $('.multiplechoice_answergroup').children('li').find('input[type="checkbox"]:not(:checked)')){
correctAnswer();
} else if($('.multiplechoice_answergroup').children('li').hasClass('True') && $('.multiplechoice_answergroup').children('li').find('input[type="checkbox"]:checked')){
correctAnswer();
} else {
incorrectAnswer();
}
};
而不是那么做
$('.multiplechoice_answergroup').children('li')
.find('input[type="checkbox"]:checked')
你應該做
$('.multiplechoice_answergroup').children('li')
.find('input[type="checkbox"]').is(":checked")
原因:
find()
返回一個在JavaScript中驗證為true的jQuery對象。 因此,第一個或第二個if表達式將始終為true, &&
的部分始終為true。
當然這里也是:
$('.multiplechoice_answergroup').children('li').find('input[type="checkbox"]').is(":not(:checked)")
怎么樣:
truefalseSubmit = function() {
$('.multiplechoice_answer input[type="checkbox"]').click(function() {
/**
* Check if the parent div where checkbox is, has the class "true"
*/
if($(this).parent().hasClass('true'))
return correctAnswer();
/**
* Answer is incorrect
*/
return incorrectAnswer();
});
}
我認為應該這樣:
truefalseSubmit = function() {
var $trueCheckbox = $('.multiplechoice_answergroup li.True input[type="checkbox"]');
var $falseCheckbox = $('.multiplechoice_answergroup li.False input[type="checkbox"]');
if ($trueCheckbox.is(':checked') && $falseCheckbox.is(':not(:checked)')) {
correctAnswer();
} else {
incorrectAnswer();
}
};
為什么不那樣呢?
的HTML:
<ul>
<li class="answer-button true">
<p>This answer is true</p>
</li>
<li class="answer-button false">
<p>This answer is false</p>
</li>
</ul>
js:
var answerHandler = function (answer) {
// do something
};
$('.answer-button').click(function () {
answerHandler($(this).hasClass('true'));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.