如何以HTML格式从javascript对象呈现文本

时间:2014-01-14 11:33:28

标签: javascript jquery html

我有一个包含两个对象的数组:

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>

我正在尝试使用vanilla javascript,并且很快会研究jQuery。

感谢任何帮助表示赞赏!

1 个答案:

答案 0 :(得分: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