[英]How do I write contents of an array to elements in DOM?
我参加了“ 如何正确学习JavaScript”的第4周,并且正在进行动态测验。 这是我的进度:
$(document).ready(function(){
var allQuestions = [
{
question: "Who is Prime Minister of the UK?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer: 0
},
{
question: "For how long is a dog pregnant?",
choices: ["9 Weeks", "9 Days", "9 Months", "9 Fortnights"],
correctAnswer: 0
}
];
var qQty = allQuestions.length
var randomNum = Math.floor(Math.random()*qQty);
var currentQ = allQuestions[randomNum];
$("h1").text(currentQ.question)
for (var i = 0; i < currentQ.choices.length; i++) {
$("label:eq(i)").text("currentQ.choices[i]")
};
});
这也是我的HTML的要点:
<form>
<h1>Q. - ?</h1>
<ul>
<li><label for="choice-1">label</label> <input type="radio" name="quiz" id="choice-1" value=""></li>
<li><label for="choice-2">label</label> <input type="radio" name="quiz" id="choice-2" value=""></li>
<li><label for="choice-3">label</label> <input type="radio" name="quiz" id="choice-3" value=""></li>
<li><label for="choice-4">label</label> <input type="radio" name="quiz" id="choice-4" value=""></li>
</ul>
<button id="next-btn">Next</button>
</form>
为了清楚起见,已减少了问题数量。 我目前正在使用jQuery尝试对DOM中的4个标签元素编写多项选择答案。
目前坏了。 我想在$("label:eq(i)")
内使用i
变量,但这没有发生。
我要修复的第一件事是四个标签。 很想知道我是否做得很好。 我意识到可能有一种更清洁的方法,所以请提出替代方案。
谢谢阿利斯泰尔
尝试以下方法:
for (var i = 0; i < currentQ.choices.length; i++) {
$("label:eq(" + i + ")").text(currentQ.choices[i]);
};
现在,您正在尝试将i用作迭代器,而不是插入i的值,而是文字字符串“ i”。 与currentQ.choices [i]的一部分相同...您正在制作一个完整的字符串,而不是从该数组项中插入值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.