显示来自 json 数据的干净列表

Display a clean list from json data

本文关键字:列表 数据 json 显示      更新时间:2023-09-26

我正在尝试在列表中显示我的json的所有元素。

我有一个包含我所有数据的变量"json"。

我真正想要的是像这样显示数据:

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

每次我尝试使用简单的"for"的东西时,它只向我显示最后一个元素。

我认为我最接近的解决方案是:

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

我是初学者,任何帮助将不胜感激!

在你给$.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));
    });
}