使用关联数组在 $.each 中获取迭代

Get iteration in $.each using assosiative array

JSON:

{
    "bk00001": {
        "path": "books/bk00001/",
        "lang": "ar",
        "title": [
            "Book 1",
            "Book 1"
        ]
    },
    "bk00002": {
        "path": "books/bk00002/",
        "lang": "ar",
        "title": [
            "Book 2",
            "Book 2"
        ]
    }
}

jQuery:

$.getJSON(catalog, function(data, status) {
    var items = [];
    $.each( data, function( id, meta ) {
        items.push( "<li class='" + id + "'>" + meta.path + "</li>" );
        items.push( "<li class='" + id + "'>" + meta.lang + "</li>" );
        items.push( "<li class='" + id + "'>" + meta.title + "</li>" );
    });

    $( "<ul/>", {
        "id": "library",
        html: items.join( "" )
    }).appendTo( "body" );

});

.. 但输出不是我所期望的,那是因为 id 返回的实际上是对象的键,而不是循环的索引。

这是预期的输出:

<ul id="library">
    <ul id="bk00001">
        <li class="path">...</li>
        <li class="lang">...</li>
        <li class="title">...</li>
        ...
    </ul>
    <ul id="bk00002">
        <li class="path">...</li>
        <li class="lang">...</li>
        <li class="title">...</li>
        ...
    </ul>
</ul>

除非有任何特殊原因不做简单的事情,否则这就是您想要的:

//...
//...
$.each( data, function( id, meta ) {
        items.push( "<ul id='" + id + "'>");
        items.push( "<li class='path'>" + meta.path + "</li>" );
        items.push( "<li class='lang'>" + meta.lang + "</li>" );
        items.push( "<li class='title'>" + meta.title + "</li>" );
        items.push( "</ul>");
    });
//...
//...

来自jquery documentation

If an object is used as the collection, the callback is passed a key-value pair each time:

我会这样做:

$.getJSON(catalog, function(data, status) {
    var library = $("<ul id='library'/>");
    $.each( data, function( id, meta ) {
        var ul = $("<ul id='" + id + "'/>");
        ul.append( "<li class='path'>" + meta.path + "</li>" );
        ul.append( "<li class='lang'>" + meta.lang + "</li>" );
        ul.append( "<li class='title'>" + meta.title + "</li>" );
        library.append(ul);
    });

    library.appendTo("body");
});