我正在参加如何正确学习JavaScript的第四周,我正在做动态测试。这是我的进步:
$(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)")变量,但它没有实现。
我想要修复的第一件事是这四个标签。我很想知道我是否在一个好的轨道上。我意识到可能有一个更清洁的方法,所以请提出替代方案。
谢谢你,阿利斯泰尔
发布于 2014-02-05 18:21:58
试一试:
for (var i = 0; i < currentQ.choices.length; i++) {
$("label:eq(" + i + ")").text(currentQ.choices[i]);
};现在,您正在尝试使用i作为迭代器,但不是插入i的值,而是插入文字字符串"i“。currentQ.choicesi的部分也一样..。您正在将该字符串设置为一个完整的字符串,而不是从该数组项中插入值。
https://stackoverflow.com/questions/21585254
复制相似问题