【问题标题】:json/js/html quiz: how can I parse json data into a for loop and if statements? [duplicate]json/js/html 测验:如何将 json 数据解析为 for 循环和 if 语句? [复制]
【发布时间】:2018-07-14 15:11:50
【问题描述】:

我有一个 json 文件:

{
  "questions": [
    {
      "title": "01. q1",
      "type": "dropdown",
      "options": [
        {
          "1",
          "2",
          "3"
        }
      ]
    },
    {
      "title": "q2",
      "type": "multiple_choice",
      "options": [
        "1",
        "2",
        "3",
        "4",
        "5"
      ]
    },

我正在尝试在 js 文件中编写一个 for 循环以遍历数据,如果问题类型是“下拉”,则显示 html 下拉选择器,“多项选择”将获得按钮等:

console.log = function(message) {
    document.getElementById('q_1').innerHTML = message;
};

console.log2 = function(message) {
    document.getElementById('q_2').innerHTML = message;
};

$.getJSON("generated.json", function(json)) {
  for (var i = 0; i<json.questions.length; i++) {
    if(json.questions[i].type=="drop_down") {

    }
  }
}

我真的很困惑如何动态地执行此操作,而不是对大多数代码进行硬编码。有没有一种方法可以简洁地编写此内容,而不必在 html 文件中写出每个选项/问题,而只需从 json 文件中读取并生成问题?

【问题讨论】:

  • function(json)) ),放在最后一个}之后。除此之外它看起来还不错。顺便说一句,您真的要覆盖控制台日志方法吗??
  • 也尽量不要混用 DOM JS 和 jQuery。它使它更加混乱
  • 也许 document.createElement 可以帮助你

标签: javascript jquery html json


【解决方案1】:

这是你可以使用它的方式:

var data = [
    {
      "title": "01. q1",
      "type": "dropdown",
      "options": ["1","2","3"]
    },
    {
      "title": "q2",
      "type": "multiple_choice",
      "options": ["1","2","3","4","5"]
    }
];
 $(document).ready(function(){
    $(".hello").append("<p>hello</p>")
    var s ="" ; 
    for(var i=0;i<data.length ; i++){
      if(data[i].type == "dropdown"){
        s += "<p>dropdown</p>";
        
      }
      else if(data[i].type == "multiple_choice"){
        s += "<p>multiple_choice</p>"
      }
    }
    
    $(".hello").append(s);
    
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hello">

</div>

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多