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

标签 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>

我现在正在尝试使用普通的 javascript 来实现它,并且很快就会研究如何使用 jQuery。

感谢任何帮助!

最佳答案

重新构建您的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

关于javascript - 如何以 HTML 形式从 javascript 对象呈现文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21112521/

相关文章:

javascript - 如何将三个单独的字段验证为日期

javascript - 这个奇怪的符号在 JavaScript 中意味着什么?

javascript - 如何在 Open Layers 3 中动态获取选定的要素属性?

javascript - Chrome 以百分比正确显示自适应图像和宽度,Firefox 不正确

javascript - 如何根据窗口大小动态更改图像/div 尺寸?

javascript - 使用js打印canvas.js图表

javascript - Jquery/Javascript 数学 : Why are these two 1 line math problems not giving the same answer?

javascript - 排除 child 的 jQuery 监听器

html - 制表符导航在表单中不起作用

javascript - 如何将字符添加到段落的行尾