2014-01-14 27 views
0

我有一個包含兩個對象的數組:如何從HTML表單的JavaScript對象渲染文本

var questions = [{question: "Is the sky blue?", choices: ["Yes", "No"], correctAnswer:0},{question: "Is water wet?", choices: ["Yes", "No"], correctAnswer:0}] 

我有一些JavaScript來使問題呈現在屏幕上用HTML:

<script> 
function askQuestion(x){ 
    var questiontest = document.getElementById('question'); 
    questiontest.innerHTML = x.question; 
} 

function loop(){ 
    for(i = 0; i < questions.length; i++){ 
    askQuestion(questions[i]); 
    } 
} 

left some stuff out here, not that relevant to question 

addEventListener('load',loop); 
</script> 

我的HTML看起來像這樣,顯示當前的問題,但不顯示questions對象中的選項文本:

<label for="choice" id="question"></label> 
<br><input type="radio" id="choice_1" name="choice" value="1"></input> 
<br><input type="radio" id="choice_2" name="choice" value="2"></input> 

使用此代碼我可以呈現問題,然後顯示兩個單選按鈕,即沒有選擇的文本。無論如何,我可以將questions對象的選項文本呈現在輻射按鈕旁邊嗎?還是我必須做一些愚蠢的事情才能使它正確呈現?

<br><input type="radio" name="choice" value="1"><p id="choice_1"></p></input> 

我試圖用JavaScript的時刻,並會很快研究使用jQuery做的香草做。

謝謝任何​​幫助讚賞!

+0

如果分組正確,將在輸入元素旁邊呈現一個標籤'' – devnull69

+0

'問題是,文本需要動態,即我可以把''但是當第二個問題被循環函數發現時,文本將保留......除非我誤會了? – Kane

回答

2

重新構造你的HTML所以你可以單獨標註的輸入,那麼就很容易

HTML

<form id="qform" action=""> 
    <fieldset> 
     <legend id="l0"></legend> 
     <label id="l1" for="c1"></label> 
     <input id="c1" type="radio" name="choice" value="1" /> 
     <br /> 
     <label id="l2" for="c2"></label> 
     <input id="c2" type="radio" name="choice" value="2" /> 
    </fieldset> 
</form> 

的JavaScript

function questionFactory() { 
    var i = 0, 
     l0 = document.getElementById('l0'), 
     l1 = document.getElementById('l1'), 
     l2 = document.getElementById('l2'); 
    return function askQuestion() { 
     if (i >= questions.length) return false; 
     l0.textContent = questions[i].question; 
     l1.selected = false; 
     l1.textContent = questions[i].choices[0]; 
     l2.selected = false; 
     l2.textContent = questions[i].choices[1]; 
     ++i; 
     return true; 
    } 
} 
var ask = questionFactory(); 
ask(); // asks q1, returns true 
ask(); // asks q2, returns true 
ask(); // returns false, there were no more questions to ask 

DEMO