如何从JSON数组创建列表? [英] How To Create List From JSON Array?
本文介绍了如何从JSON数组创建列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在理解数组和循环时遇到问题,因此此任务令我有些困惑.这是我的东西;
I have problem understanding arrays and loops, therefore this task is a bit confusing to me. Here's my stuff;
JSON
{
"states": [
{
"name":"johor" ,
"command":"view_johor" },
{
"name":"selangor" ,
"command":"view_selangor" },
{
"name":"melaka" ,
"command":"view_melaka" },
{
"name":"kuala lumpur" ,
"command":"view_kl" },
{
"name":"penang" ,
"command":"view_penang" }
]
}
JAVASCRIPT
$(function(){
$.ajax({
type : 'GET',
url : 'scripts/list.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result){
$.each(result, function(index, val){
for(var i=0; i < val.length; i++){
var item = val[i];
console.log(item.name)
}
});
},
});
});
我的问题是我不知道如何使用循环,这样我的HTML才会返回:
<ul>
<li><a href="#view_johor">Johor</a></li>
<li><a href="#view_selangor">Selangor</a></li>
<!-- and so on, dynamically depending on json... -->
</ul>
我可以通过console.log(item.name)
等访问数据,但是我无法操纵数据,因此数据将像我想要的那样显示.我什至不知道用来搜索问题的术语,因为我知道这就像基本的数组内容一样..在此先感谢您的帮助!
I can access the data via console.log(item.name)
and such, but I can't manipulate the data so that it will display like I wanted. I don't even know the term to use to search for questions, as I know this is like basic array stuff....Thank you in advance for your help!
推荐答案
u可以做到:
$(function(){
$.ajax({
type : 'GET',
url : 'scripts/list.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result){
var buffer="";
$.each(result, function(index, val){
for(var i=0; i < val.length; i++){
var item = val[i];
console.log(item.name);
buffer+=" <li><a href='#"+item.name+"'>"+item.name+"</a></li> <li><a href='#"+item.command+"'>"+item.command+"</a></li>";
}
$('ul').html(buffer);
});
}
});
});
这篇关于如何从JSON数组创建列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文