[英]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) <img src="imgs/printer.jpg" alt="question image"><br/>
<input type="checkbox" name="q4" value="b">B) <img src="imgs/keyboard.jpg" alt="question image"><br/>
<input type="checkbox" name="q4" value="c">C) <img src="imgs/scanner.jpg" alt="question image"><br/>
<input type="checkbox" name="q4" value="d">D) <img src="imgs/speakers.jpg" alt="question image"><br/>
</div>
<br>
<input type="button" name="submit" value="Check Answer" onclick="q4()">
<h3 id="Answer4"> </h3>
</div><!-- end of question four -->
考慮線
if(a4[i].value == "a" && a4[i].value == "d") {
a4[i].value
如何成為"a"
而成為"d"
?
您可能想要||
(“或”),可能與在循環完成后檢查correctAnswers
等於2結合在一起。
您的代碼成為“隱式全球性恐怖”的犧牲品(這是我貧乏的小博客上的帖子) 。 確保在有意義的最窄范圍內聲明變量(例如i
和correctAnswers
),如果是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) <img src="imgs/printer.jpg" alt="question image"><br/> <input type="checkbox" name="q4" value="b">B) <img src="imgs/keyboard.jpg" alt="question image"><br/> <input type="checkbox" name="q4" value="c">C) <img src="imgs/scanner.jpg" alt="question image"><br/> <input type="checkbox" name="q4" value="d">D) <img src="imgs/speakers.jpg" alt="question image"><br/> </div> <br> <input type="button" name="submit" value="Check Answer" onclick="q4()"> <h3 id="Answer4"> </h3> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.