gpt4 book ai didi

jquery - 使用 jQuery 嵌套无序列表的对象

转载 作者:行者123 更新时间:2023-12-01 06:43:56 24 4
gpt4 key购买 nike

我一直在尝试将此对象转换为无序列表,但我需要将其合并到类别中。

var snippets = [
{title: 'snippet 1', content: 'hello there 1', category: 'javascript'},
{title: 'snippet 2 ', content: 'hello there 2', category: 'wordpress'},
{title: 'snippet 3', content: 'hello there 3', category: 'javascript'},
{title: 'snippet 4', content: 'hello there 4', category: 'general'},
{title: 'snippet 5', content: 'hello there 5', category: 'general'}
];

预期输出是:

<ul>
<li>javascript
<ul>
<li>snippet 1</li>
<li>snippet 2</li>
</ul>
</li>
<li>wordpress
<ul>
<li>snippet 1</li>
<li>snippet 2</li>
</ul>
</li>
</ul>

我一直在尝试使用 $.each 来做到这一点,但是对于我的文件,我无法理解它。我也愿意使用 UnderscoreJS。

$('body').append('<ul class="categories"></ul>');

$.each(snippets, function(i, v) {
var data = '<li class="category">'+ v.category +' ';
data += '<ul class="item"> <li> ' + v.title + ' </li> </ul>';
data += '</li>';

$(data).appendTo('.categories');
});

输出不是预期的:

<ul class="categories">
<li class="category">javascript
<ul class="item">
<li> snippet 1 </li>
</ul></li>
<li class="category">wordpress
<ul class="item">
<li> snippet 2 </li>
</ul>
</li>
<li class="category">javascript
<ul class="item">
<li> snippet 3 </li>
</ul>
</li>
<li class="category">general
<ul class="item">
<li> snippet 4
</li>
</ul>
</li>
<li class="category">general
<ul class="item">
<li> snippet 5
</li>
</ul>
</li>
</ul>

谁能给我提示吗?

最佳答案

内嵌注释作为说明:

var snippets = [
{title: 'snippet 1', content: 'hello there 1', category: 'javascript'},
{title: 'snippet 2 ', content: 'hello there 2', category: 'wordpress'},
{title: 'snippet 3', content: 'hello there 3', category: 'javascript'},
{title: 'snippet 4', content: 'hello there 4', category: 'general'},
{title: 'snippet 5', content: 'hello there 5', category: 'general'}
];

// Create the UL that will contain all the categories
var ul = $("<ul>").addClass("categories");
// Use an object as a map of category to sublist
var lists = Object.create(null);
// Loop through the snippets
snippets.forEach(function(snippet) {
// Get the sublist for this category
var list = lists[snippet.category];
if (!list) {
// Don't have one yet, create it
list = lists[snippet.category] = $("<ul>");
// Create the item that will contain it in the main list
var item = $("<li>").addClass("category").text(snippet.category);
// Add the sublist to the item, and the item to the main list
item.append(list);
ul.append(item);
}
// Add this entry to the sublist
list.append($("<li>").addClass("item").text(snippet.title));
});
// Done building, add the main list to the doc
ul.appendTo(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于jquery - 使用 jQuery 嵌套无序列表的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42737615/

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