2014-02-05 55 views
0

我參加How to Learn JavaScript Properly的第4周,我正在進行動態測驗。這裏是我的進步:如何將數組的內容寫入DOM中的元素?

$(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變量,但它沒有發生。

我想解決的第一件事是四個標籤。想知道我是否在一個好的軌道上。我意識到可能有更清晰的方式,所以請建議替代方案。

感謝,阿利斯泰爾

回答

1

試試這個:現在

for (var i = 0; i < currentQ.choices.length; i++) { 
    $("label:eq(" + i + ")").text(currentQ.choices[i]); 
}; 

,你試圖使用我作爲一個迭代器,而不是插入我的價值,但文本字符串「我」。與currentQ.choices [i]的一部分一樣...您正在創建一個完整的字符串,而不是從該數組項中插入值。

+0

是的。固定。 $(「label:eq(」+ i +「)」)。text(currentQ.choices [i]) 感謝mori :) –

+0

我很快就會有更多的問題,我應該在這裏張貼或張貼其他問題題? –

+0

我認爲一般的感覺是,如果它與第一個問題中的問題沒有直接關係,那麼您應該開另一個問題。 –

相關問題