我有一个如下所示的JSON
{
"gists": [
{
"name": "Get the title",
"id": "beaf8a106e76f4bb82a85ca3a7707a78",
"category": "Function"
},
{
"name": "Get the content",
"id": "c6ae7c55aa27f8b6dbeb15f5d72762ec",
"category": "Uncategorized"
}
]
}
我想通过JavaScript获取和获取HTML。如下所示:
<ul>
<li>Name: Get The title, ID: beaf8a106e76f4bb82a85ca3a7707a78, Function: Function</li>
<li>Name: Get The content, ID: c6ae7c55aa27f8b6dbeb15f5d72762ec, Function: Uncategorized</li>
</ul>
我已经尝试过这种方式:http://jsfiddle.net/ehsansajjad465/SLHTA/10/
但是,我不确定如何在一行中获取值,我想使用纯JS来实现。另外,我的JSON将来自外部链接。 http://rasel.tech/gist.json
这可能是一个非常愚蠢的问题。抱歉:(
答案 0 :(得分:0)
您可以使用JSON.stringify
对对象进行字符串化,而我使用正则表达式从字符串中删除{}
。
let obj = {"gists": [{"name": "Get the title","id": "beaf8a106e76f4bb82a85ca3a7707a78","category": "Function"},{ "name": "Get the content","id": "c6ae7c55aa27f8b6dbeb15f5d72762ec","category": "Uncategorized"}]}
let li = document.getElementById('list');
obj.gists.forEach( e => {
let ele = document.createElement('li')
ele.innerHTML = `${JSON.stringify(e).replace(/[{}]/g,'')}`
li.appendChild(ele);
})
<ul id='list'>
</ul>
答案 1 :(得分:0)
如果您希望将项目放在一行中,可以使用CSS来完成。
您可以在white-space:nowrap;
中添加ul
,在display: inline
中添加li
。我只是在编辑您添加的小提琴。
var data = {
"qA": [{
"question": "How deep is the ocean",
"answer": [
"quite deep",
"very deep",
"no deep at all"]
}, {
"question": "How high is the sky",
"answer": [
"real high",
"high enough",
"not that high"]
}]
};
var html = "";
$.each(data.qA, function (index, item) {
//console.log(item);
html += "<ul>" + item.question;
$.each(item.answer, function (index1, item1) {
html += " <li> ("+index1+ ") " + item1 + "</li>";
});
html += "</ul>";
});
$("#container").append(html);
ul{
white-space:nowrap;
}
ul li{
display: inline
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container"></div>
答案 2 :(得分:0)
使用香草JS,您可以使用forEach方法遍历数组并相应地构造li元素。
var data = {
"gists": [
{
"name": "Get the title",
"id": "beaf8a106e76f4bb82a85ca3a7707a78",
"category": "Function"
},
{
"name": "Get the content",
"id": "c6ae7c55aa27f8b6dbeb15f5d72762ec",
"category": "Uncategorized"
}
]
};
var container = document.querySelector('#container');
var ul = document.createElement('ul');
data.gists.forEach(function (item) {
var li = document.createElement('li');
li.textContent = 'Name: ' + item.name + ', ID: ' + item.id + ', Function: ' + item.category;
ul.appendChild(li);
});
container.appendChild(ul);
<div id="container"></div>