【问题标题】:jQuery : Wrap separate sets of <ul></ul> tags around multiple groups of list items <li></li>jQuery : 围绕多组列表项 <li></li> 包裹单独的 <ul></ul> 标记集
【发布时间】: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个父列表,每个都有多个子列表项。 (结构见所附屏幕截图。)

我现在想做的是将每组子列表项包装在自己的一组中

    标签,以便在每种情况下创建适当的嵌套无序列表。

    提前感谢您为此提供的任何帮助。

    【问题讨论】:

    标签: jquery ajax append html-lists


    【解决方案1】:

    您应该在 class="cat" 列表项中嵌套一个 UL 元素,然后将子元素附加到该 UL 元素。

    在类别中嵌套 UL 元素,注意下面 html var 中的新 UL 元素

    let html = data.categories.map(c => `<li class="cat" catid=${c.id}><a href="#">${c.name}</a><ul></ul></li>`);
    

    然后使用

    附加到那个嵌套的 UL
    $("li[categoryid|='360002246652']").appendTo( $("li[catid|='360002246652'] ul"));
    

    【讨论】:

    • 非常感谢。这就说得通了。幸运的是,我设法通过使用 insertAfter 方法(而不是 appendTo 方法)解决了最初的问题。现在——我实际上不再需要嵌套的“UL”出现在输出中了。
    【解决方案2】:

    我通过在我的“let html”语句中添加一组外部&lt;ul&gt;&lt;/ul&gt; 标签来实现我想要的,如下所示:

    let html = data.categories.map(c => `<ul><li class="cat" catid=${c.id}><a 
    href="#">${c.name}</a></li></ul>`);
    

    现在,每个父列表项都包含在一个单独的无序列表中。

    再次感谢您提供的反馈。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 2015-08-28
      • 2019-01-24
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      相关资源
      最近更新 更多