我正在尝试用分数创建一个小型调查。我想这样做,一旦用户达到分数“4”,它就会发出一些消息。我写了if if statment,但由于某种原因它从不警告。但如果我手动将得分变量改为4,一切都按预期工作。
我哪里错了?
以下是代码:
<script>
var score = 0;
function checkQuestionOne (){
var jautViens = document.getElementById('jaut1Pirm');
var jautDivi = document.getElementById('Jaut1Otra');
var jautTris = document.getElementById('Jaut1Tres');
var jautCetri = document.getElementById('Jaut1Cetu');
if(jautViens.checked) {
alert(++score)
}else if(jautDivi.checked || jautTris.checked || jautCetri.checked) {
alert("Nepareizi")
}else{
alert("Izvēlies opciju!")
}
}
if (score == 4){
alert(score);
}else{
}
答案 0 :(得分:2)
如果功能
,您需要检查条件
var score = 0;
function checkQuestionOne() {
var jautViens = document.getElementById('jaut1Pirm');
var jautDivi = document.getElementById('Jaut1Otra');
var jautTris = document.getElementById('Jaut1Tres');
var jautCetri = document.getElementById('Jaut1Cetu');
if (jautViens.checked) {
++score;
//since value of score is changed only in this block you can place the if block here
if (score == 4) {
alert('score is 4');
}
} else if (jautDivi.checked || jautTris.checked || jautCetri.checked) {
alert("Nepareizi")
} else {
alert("Izvēlies opciju!")
}
//keep the if block here, if there are multiple blocks in which the value of score is changed
}
<h1>Pirmais jautājums (1. pareizā)</h1>
<input type="radio" name="jaut1" id="jaut1Pirm" value="pirma" />Šī ir pirmā atbilde
<br/>
<input type="radio" name="jaut1" id="Jaut1Otra" value="otra" />Šī ir otrā atbilde
<br/>
<input type="radio" name="jaut1" id="Jaut1Tres" value="tresa" />Šī ir trešā atbilde
<br/>
<input type="radio" name="jaut1" id="Jaut1Cetu" value="ceturta" />Šī ir ceturtā atbilde
<br/>
<br/>
<button type="submit" onclick="checkQuestionOne();">Spied</button>
当您将其保留在函数之外时,if
条件仅评估一次,但每次score
的值更改时都需要检查它。