我正在尝试创建一个带有分数的小型调查。我想让它一旦用户达到分数“4”,它就会提醒一些消息。我为它编写了 if 语句,但由于某种原因它从不发出警报。但如果我手动将分数变量更改为 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{
}
最佳答案
您需要检查该函数的条件
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
的值发生更改时您都需要检查它。
关于Javascript if 语句未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31287237/