2014-01-14 26 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