繁体   English   中英

使用循环的if和逻辑(&&)的javascript函数

[英]A javascript function, using a loop, if and logic (&&)

我正在使用具有四个复选框的javascript函数,其中两个是正确的答案。 我试图使用以下代码。

function q4() {
    var a4 = document.getElementsByName('q4');
        for(i=0; i < a4.length; i++) {
            if(a4[i].checked) {
                if(a4[i].value == "a" && a4[i].value == "d") {
                correctAnswers++;
                alert('This works');
                }
            }// end if first if
        }// end of for loop
}// end of function q4

如果值a AND d正确,则应该发出警报。

HTML:

<!-- Question 4 -->  
    <div class="question-box">  
        <div class="question"><h3>Question Four: Identify two output devices from the images.</h3></div>
        <div class="answers">  
            <input type="checkbox" name="q4" value="a">A)&nbsp;<img src="imgs/printer.jpg" alt="question image"><br/>
            <input type="checkbox" name="q4" value="b">B)&nbsp;<img src="imgs/keyboard.jpg" alt="question image"><br/>
            <input type="checkbox" name="q4" value="c">C)&nbsp;<img src="imgs/scanner.jpg" alt="question image"><br/>
            <input type="checkbox" name="q4" value="d">D)&nbsp;<img src="imgs/speakers.jpg" alt="question image"><br/>
        </div>
        <br>
    <input type="button" name="submit" value="Check Answer" onclick="q4()">
    <h3 id="Answer4">&nbsp;</h3>
    </div><!-- end of question four -->

考虑线

if(a4[i].value == "a" && a4[i].value == "d") {

a4[i].value如何成为"a" 成为"d"

您可能想要|| (“或”),可能与在循环完成后检查correctAnswers等于2结合在一起。


您的代码成为“隐式全球性恐怖”的牺牲品(这是我贫乏的小博客上的帖子) 确保在有意义的最窄范围内声明变量(例如icorrectAnswers ),如果是correctAnswers ,请确保对其进行初始化(也许使用0 )。


更新的代码:

 function q4() { var a4 = document.getElementsByName('q4'); var correctAnswers = 0; // declare and initialize `correctAnswers` for (var i = 0; i < a4.length; i++) { // declare `i` if (a4[i].checked) { if (a4[i].value == "a" || a4[i].value == "d") { correctAnswers++; } } } if (correctAnswers == 2) { console.log("Correct!"); } else { console.log("Incorrect"); } } 
 <div class="question-box"> <div class="question"> <h3>Question Four: Identify two output devices from the images.</h3> </div> <div class="answers"> <input type="checkbox" name="q4" value="a">A)&nbsp;<img src="imgs/printer.jpg" alt="question image"><br/> <input type="checkbox" name="q4" value="b">B)&nbsp;<img src="imgs/keyboard.jpg" alt="question image"><br/> <input type="checkbox" name="q4" value="c">C)&nbsp;<img src="imgs/scanner.jpg" alt="question image"><br/> <input type="checkbox" name="q4" value="d">D)&nbsp;<img src="imgs/speakers.jpg" alt="question image"><br/> </div> <br> <input type="button" name="submit" value="Check Answer" onclick="q4()"> <h3 id="Answer4">&nbsp;</h3> </div> 

暂无
暂无

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

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