OK、ここで私はクイズアプリケーションを作成しようとしていますが、何が間違っているのかを調べるのに8時間以上かかる。私はちょうどあきらめるので、できるならplsは私を助けます。状況をDOMを使用して質問の回答を選択するラジオ入力を作成し、次のをクリックするたびに別の質問がdivタグに表示され、前のdivタグは削除されます。私はすべての質問が終わった後に、アラートウィンドウでユーザーに通知するか、または何人が正しい答えを得たかについて何かを通知する方法で結果を保存します。問題は、私は何が間違っているのか分かりません。Javascriptラジオボタンの値をdiv位置に設定
answers = document.getElementsByName('quiz');
if(answers[1].checked){
alert("gj");
}
これは、ブラウザのコンソールで正常に動作し、ユーザーが選択したラジオボタンの数1.あれば、それは私に警告が、私は私のスクリプト内でこれを入れたとき、それは何もしません。 私はstart()関数全体をどのように作成したかに問題があると推測していますが、私はその頭の中で頭を囲むことができません。
完全なコード: 動的クイズ
var allQuestions = [{
question: "Question1?",
choices: ["Answer1", "Answer2", "Answer3", "Answer4"],
CorrectAnswer:0},
{
question: "Question2?",
choices: ["Answer6", "Answer7"],
CorrectAnswer:0}
];
var currentQuestion=0;
var currentAnswer=0;
var correctAnswer=0;
var answers;
var div2;
function createDiv(){
var div=document.createElement("div");
div2=document.getElementById("content").appendChild(div);
}
function createQuestion(question){
var q = document.createElement('p');
q.innerHTML=question;
div2.appendChild(q);
}
function createRadio(id){
var radio = document.createElement('input');
radio.setAttribute("type","radio");
radio.setAttribute("name","quiz");
radio.setAttribute("id",id);
div2.appendChild(radio);
}
function createLabel(id,text){
var lab = document.createElement('label');
lab.setAttribute("id",id);
lab.setAttribute("for",id);
lab.innerHTML=text;
div2.appendChild(lab);
}
function checkAnswer(){
answers = document.getElementsByName('quiz');
if(answers[1].checked){
alert("gj");
}
}
function remover(){ //removes content for next question
var myNode = document.getElementById("content");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
function start(){
remover();
createDiv();
createQuestion(allQuestions[currentQuestion].question);
//create all radio answers for question in div
for (var i = 0; i<allQuestions[currentQuestion].choices.length;i++){
createDiv();
createRadio(allQuestions[currentQuestion].choices[i]);
createLabel(allQuestions[currentQuestion].choices[i],allQuestions[currentQuestion].choices[i]);
}
checkAnswer();
currentQuestion++;
if (currentQuestion === allQuestions.length){ //just sto stop from going infinite
currentQuestion=allQuestions.length-1; }
}
</script>
</head>
<body onload=start()>
<div id="main">
<div id="content"></div>
</div>
<div id="butn">
<input type="submit" value="Start" onClick="start()">
</body>
</html>
スニペット、ということは可能ですか?それとも私は完全に間違ったアプローチをしていますか? – Energizem
@Energizem質問のリストを更新するたびにcheckAnswer関数を使用して最後の答えが正しいかどうかをチェックすることができます。また、正しい答えのカウンタを保持することもできます – user2314737
@ user2314737 "document.getElementsByNameクイズ "); は、appendChild()で動的に追加されますので、document.getElementsByNameで検出されません。"は正しくありません.getElementsは現在のリストをquerySelectorとして取得しないので更新します。 –