gpt4 book ai didi

javascript - 如何在单选按钮标签中添加文本?

转载 作者:行者123 更新时间:2023-11-28 14:15:22 24 4
gpt4 key购买 nike

我使用带有问题和单选按钮的数组来选择用户选择的值。

我知道如何动态更改按钮内的文本。

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 标记。

关于javascript - 如何在单选按钮标签中添加文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57716656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com