2013-11-03 73 views
0

我试图在列表中显示我的json的所有元素。从json数据中显示一个干净的列表

我有一个var“json”包含我所有的数据。

我到底要为显示这样的DATAS:

<ul> 
    <li>title + "of the first element"</li> 
    <li>title + "of the second element"</li> 
    <li>title + "of the third element"</li> 
    </ul> 

每次我尝试的东西用一个简单的“为”,只显示我的最后一个元素。

我最接近的解决方案是用这个,我认为:

function displayJson(){ 

    $.each(json, function(key, value) { 
     $(this).html("<li>" + json[key].title + "</li>"); 
    }); 

} 

我是初学者,任何帮助将非常感激!

+2

请提供我们要显示 – tomahim

+0

一个变化的JSON的例子编辑你的问题我甚至可以只用问题中的信息来建议:使用'value.title'而不是'json [key] .title'。 –

回答

1

在你给$.each功能,this将在json对象的项目,不是一个DOM元素的值,所以不能产生输出的方式。

假设json是指包含对象的对象,每个都有一个title属性,则:

var $ul = $("some selector for the list"); 
var json = /*...wherever you're getting the object from... */; 
displayJson($ul, json); 

function displayJson($ul, json) { 
    $ul.empty(); // If it might have something in it 
    $.each(json, function(key, value) { 
     $ul.append($("<li>").html(value.title)); 
    }); 
} 
+1

谢谢你的解释! – CompteDev

相关问题