简体   繁体   English

Javascript if语句无法按预期工作

[英]Javascript if statement doesn't work as expected

I'm trying to create a small survey with a score. 我正在尝试创建一个带有分数的小调查。 I want to make it so once user reaches score "4", it alerts some message. 我想做到这一点,以便一旦用户达到分数“ 4”,它就会提醒一些消息。 I wrote if statment for it, but for some reason it never alerts. 我为此写了if陈述,但由于某种原因它从未发出警报。 But if I manually change score variable to 4, everything works as expected. 但是,如果我将Score变量手动更改为4,则一切都会按预期进行。

Where am I going wrong? 我要去哪里错了?

Here's the code: 这是代码:

http://jsfiddle.net/uy9kq9mx/ http://jsfiddle.net/uy9kq9mx/

<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{

}

You need to check the condition if the function 您需要检查条件是否功能

 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> 

When you keep it outside of the function, the if condition is evaluated only once, but you need to check it everytime the value of score is changed. 当您将其保留在函数之外时, if条件仅被评估一次,但是每次score值更改时都需要检查它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM