javascript – 使用JSON数据在html中填充ul
作者:互联网
嗨我试图用JSON填充mu在html中,我已经尝试了很多来自这个网站的解决方案,但我没有太多的运气,任何建议将不胜感激.谢谢
我的代码:
<script>
$.getJSON('/simplepie/round/alltables.json', function (data) {
var o = null;
var myArray = new Array();
document.open();
for( var i = 0; i < data.length; i++ )
{
o = data[i];
myArray.push('<li>' + o.title + '</li>');
//document.write(o.source + " <br>" + o.description + "<br>") ;
myArray.push(o.source);
makeUL(o.source);
}
//document.close();
// document.write('Latitude: ' + data.id + '\nLongitude: ' + data.title + '\nCountry: ' + data.description);
function makeUL(array) {
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
});
</script>
</head>
<body>
<ul id="ct"></ul>
</body>
JSON结构
[{"id":"1","source":"Articles | Mail Online",
"time_date":"1422720360",
"title":"Rouhani accuses Iranian hardliners of ",
"description":"DUBAI, Jan 31 (Reuters) - Iranian President Hassan Rouhani",
"link":"http:\/\/www.dailymail.co.uk\/wires\/reuters\/article-2934402\/Rouhani-accuses-Iranian-hardliners-cheering-atom-talks.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490",
"image":"http:\/\/i.dailymail.co.uk\/i\/pix\/m_logo_154x115px.png"}]
解决方法:
用这个替换你的循环:
获取您的列表,因为它已经存在于您的身体中< ul id =“ct”>< / ul>:
var ul = document.getElementById("ct");
然后使用javascript创建li并将其附加到列表中:
for( var i = 0; i < data.length; i++ )
{
o = data[i];
var li = document.createElement("li");
li.appendChild(document.createTextNode(o.title));
ul.appendChild(li);
}
您不需要MakeUL功能
这是一个帮助你的JS小提琴:http://jsfiddle.net/loanburger/6nrx1zkj/
标签:javascript,jquery,json,html-lists 来源: https://codeday.me/bug/20190824/1711802.html