
[英]Vanilla Javascript - How to loop through just elements in the DOM using querySelectorAll('*')
[英]How to loop through following blocks using vanilla JavaScript function?
我是JavaScript的初學者,我試圖做一個問答游戲,以學習操縱DOM。 我知道也有類似的問題,很遺憾,我找不到我的情況的答案。
我有這個HTML結構:
<div class="wrapper">
<h1>Test your knowledge</h1>
<form class="box" id="quizBox1">
<div class="question1">
<p>What is the name of George?</p>
<div class="inputs">
<input id="answer" type="radio" name="quiz1" value="wrong">Tom
<input id="answer" type="radio" name="quiz1" value="correct">George
<input id="answer" type="radio" name="quiz1" value="wrong">John<br>
<input type="submit" name="quiz1" class="button" id="answer" onclick="return quiz();">
</div>
</div>
</form>
<form class="box" id="quizBox2">
<div class="question2">
<p>Which one is blue?</p>
<div class="inputs">
<input id="answer" type="radio" name="quiz2" value="wrong">Banana
<input id="answer" type="radio" name="quiz2" value="correct">Sky
<input id="answer" type="radio" name="quiz2" value="wrong">Red BMW<br>
<input type="submit" name="quiz2" class="button" id="answer" onclick="return quiz();">
</div>
</div>
</form>
</div>
基本上,我有兩種形式的問題,形式各異(但我想在想清楚之后再添加更多形式)。 我已經設法找出如何跟蹤是否選擇了正確答案並添加正確答案的數量以顯示在末尾。
而這個JavaScript:
function quiz () {
var amountCorrect = 0;
for(var i = 1; i <=12; i++)
var radios = document.getElementsByName("quiz"+1);
// var questions = document.getElementByIdName("quizBox"+1);
for(var j = 0; j < radios.length; j++) {
var radio = radios[j];
if (radio.value === "correct" && radio.checked) {
alert("correct");
amountCorrect ++;
questions.style("display", "none");
} else if (radio.checked && radio.value != "correct") {
alert("not");
}
}
alert(amountCorrect);
}
我在這里的問題是,一旦回答了當前的問題,我將不知道如何交換到另一個問題。 我每次嘗試設置一個新變量並顯示下一個問題塊,同時隱藏其他問題,但是我找不到使它起作用的方法。 如果可能的話,我想在香草JS中實現此功能,而無需使用jQuery。 感謝您提供任何幫助,即使它可以幫助我走上正確的道路!
您可以對測驗功能進行一些小的更改。 添加一個參數,使其知道要查看的單選按鈕。
function quiz(p) {
.....getElementsByName(p);
}
然后將其稱為不同的集合。 測驗( “quiz1”);
另外,要顯示和隱藏表單,您可以執行以下操作
let a = document.gelElementById("quizBox1);
a.style.display = "none";
並在需要顯示該屬性時將其更改為block
。
有一個通用的模式。
如果您有一堆測驗題,例如
<div class='quiz' id='quiz1'>
...
</div>
<div class='quiz' id='quiz2'>
...
</div>
首先選擇它們並使其隱藏
let quizzes = document.querySelectorAll(".quiz");
for (let i = 0; i < quizzes.length; i++) {
quizzes[i].style.display = "hidden";
}
然后設置您要顯示的那個
document.getElementById(quizIWantToShow).style.display = "block";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.