我有一个json文件:
{
"questions": [
{
"title": "01. q1",
"type": "dropdown",
"options": [
{
"1",
"2",
"3"
}
]
},
{
"title": "q2",
"type": "multiple_choice",
"options": [
"1",
"2",
"3",
"4",
"5"
]
},
我正在尝试在js文件中编写for循环以便浏览数据,如果问题类型是“dropdown”,则显示html下拉选择器,“multiple choice”会获得按钮等:
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文件中读取并生成问题?
答案 0 :(得分:0)
这是你可以使用它的方式:
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>