【发布时间】:2020-08-02 07:25:24
【问题描述】:
我正在构建一个依赖 AJAX 从 JSON 文件中提取数据的分层菜单。我进行了两个单独的 AJAX 调用——每个调用都创建一个单独的无序列表 (UL)。以下是 AJAX 调用:
//AJAX calls to the Category JSON file
var $requestcategories = $.ajax({
url: 'https://MyURL/categories.json',
dataType: 'json',
type: 'get',
cache: 'false',
success: function(data) {
let $ul = $('<ul id="categories" />');
let html = data.categories.map(c => `<li class="cat" catid=${c.id}><a href="#">${c.name}</a></li>`);
$ul.append(html).appendTo('#testnav');
}
});
//AJAX calls to the the Section JSON file
var $requestsections = $.ajax({
url: 'https://MyURL/sections.json',
dataType: 'json',
type: 'get',
cache: 'false',
success: function(data) {
let $ul = $('<ul id="sections" />');
let html = data.sections.map(s => `<li class="sec" secid=${s.id} categoryid=${s.category_id}
parentsecid=${s.parent_section_id}><a href="${s.html_url}">${s.name}</a></li>`);
$ul.append(html).appendTo('#testnav');
创建两个列表后,我使用 jQuery appendTo 方法将第二个 UL 中的列表项移动到第一个 UL 中的适当位置。以下是移动各个部分的代码:
//Code that moves each individual section to its parent category
$("li[categoryid|='360002246652']").appendTo( $("li[catid|='360002246652']"));
$("li[categoryid|='360002246672']").appendTo( $("li[catid|='360002246672']"));
$("li[categoryid|='360002254991']").appendTo( $("li[catid|='360002254991']"));
$("li[categoryid|='360002255011']").appendTo( $("li[catid|='360002255011']"));
$("li[categoryid|='360002255031']").appendTo( $("li[catid|='360002255031']"));
$("li[categoryid|='360002255051']").appendTo( $("li[catid|='360002255051']"));
移动后,有6个父列表,每个都有多个子列表项。 (结构见所附屏幕截图。)
我现在想做的是将每组子列表项包装在自己的一组中
提前感谢您为此提供的任何帮助。
【问题讨论】:
-
请提供一个最小的、可重现的例子:stackoverflow.com/help/minimal-reproducible-example
标签: jquery ajax append html-lists