我正在使用带有问题和单选按钮的数组来选择用户选择的值。
我知道如何动态更改按钮内的文本。
document.getElementById('rad1').innerHTML = arrayQuestion[i].ansA;
但是我不知道在为单选按钮使用标签时如何执行此操作。
<html>
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title></title>
</head>
<body>
<form id="formEl">
<h2 id="question"></h2>
<input type="radio" id="rad1" name="rad" value="choice 1">
<label for="rad1"></label>
<input type="radio" id="rad2" name="rad" value="choice 2">
<label for="rad2"></label>
<input type="radio" id="rad3" name="rad" value="choice 3">
<label id="labelRad3"></label>
<input type="radio" id="rad4" name="rad" value="choice 4">
<label for="rad4"></label>
<button id="previous" type="button" class="userSelection">Previous</button>
<button id="next" type="button" class="userSelection">Next</button>
<button id="submit">Submit</button>
</form>
</body>
<script src = js/app.js></script>
</html>
class Question {
constructor(question, ansA, ansB, ansC, ansD, answer) {
this.question = question;
this.ansA = ansA;
this.ansB = ansB;
this.ansC = ansC;
this.ansD = ansD;
this.answer = answer;
};
checkAns(ansSelected, answer) {
if (ansSelected === answer) {
console.log('Well Done')
};
};
};
//Questions
var questionOne = new Question('Where is Creete?',
'Barcalona', 'Greece', 'Dubi', 'Ireland', 'Greece');
var questionTwo = new Question('How many times have Liverppool won the Champions Legue?',
'1', '4', '6', '5', '6');
var questionThree = new Question('Where was the first Godfather in the mafia from?',
'Milan', 'Gunoa', 'Rome', 'Napoli', 'Napoli');
//Index of the array with the questions array
var i = 0;
const arrayQuestion = [questionOne, questionTwo, questionThree];
//Displaying the first index of the question array on load up
document.getElementById('question').innerHTML = arrayQuestion[i].question;
document.getElementById('rad1').innerHTML = arrayQuestion[i].ansA;
document.getElementById('rad2').innerHTML = arrayQuestion[i].ansB;
document.getElementById('labelRad3').innerHTML = arrayQuestion[i].ansC;
document.getElementById('rad4').innerHTML = arrayQuestion[i].ansD;
结果应在相应的标签中动态填充答案
您可以简单地提供单选按钮 ID。
<label id="rad1-label" for="rad1"></label>
然后你可以使用
document.getElementById("rad1-label").innerText = arrayQuestion[i].ansA;
使用innerText
而不是innerHTML
除非您需要在要呈现的答案中使用HTML 标记。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句