gpt4 book ai didi

jquery - 使用关联数组获取 $.each 中的迭代

转载 作者:行者123 更新时间:2023-12-01 07:50:04 25 4
gpt4 key购买 nike

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 - 使用关联数组获取 $.each 中的迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31009042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com