我参加了How to Learn JavaScript Properly的第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个标签元素编写多项选择答案。
目前已经破产了。我想在i
中使用$("label:eq(i)")
变量,但它没有发生。
我想解决的第一件事是四个标签。很想知道我是否走得很好。我意识到可能有一种更清洁的方式,所以请建议替代方案。
谢谢,Alistair
答案 0 :(得分:1)
请改为尝试:
for (var i = 0; i < currentQ.choices.length; i++) {
$("label:eq(" + i + ")").text(currentQ.choices[i]);
};
现在,您尝试使用i作为迭代器,但不插入i的值,而是插入文字字符串“i”。与currentQ.choices [i]的部分相同......你正在制作一个完整的字符串,而不是从该数组项中插入值。