我有一个嵌套列表,其中包含一些字符串数据。我想要的是遍历第一个列表并检查每个“一级”项目,并将相同的项组合在一起。然后,我想用逗号在字符串中拆分,以便创建单独的项目,将列表号1中具有相同字符串值的所有项目嵌套到该项目中。我想通过一级迭代进行尝试,并将每个唯一性添加到数组中,然后以某种方式将二级配对,即那个配对。
开始列表:
<ul>
<li class="level-one">
flowers,trees
<ul>
<li class="level-two">
gardening
</li>
</ul>
</li>
<li class="level-one">
flowers,trees
<ul>
<li class="level-two">
planting
</li>
</ul>
</li>
<li class="level-one">
orange,lemon
<ul>
<li class="level-two">
fruit
</li>
</ul>
</li>
<li class="level-one">
orange,lemon
<ul>
<li class="level-two">
citrus
</li>
</ul>
</li>
</ul>
预期结果:
<ul>
<li class="level-one">
flowers
<ul>
<li class="level-two">
gardening
</li>
<li class="level-two">
planting
</li>
</ul>
</li>
<li class="level-one">
trees
<ul>
<li class="level-two">
gardening
</li>
<li class="level-two">
planting
</li>
</ul>
</li>
<li class="level-one">
orange
<ul>
<li class="level-two">
fruit
</li>
<li class="level-two">
citrus
</li>
</ul>
</li>
<li class="level-one">
lemon
<ul>
<li class="level-two">
fruit
</li>
<li class="level-two">
citrus
</li>
</ul>
</li>
</ul>
答案 0 :(得分:1)
如果您将其逐步分解最简单;
level-one
文本并以逗号分隔level-two
个列表项level-two
个项目,并且不清楚是否要这样做)注意:我创建了一个数组objs
,它将包含最后插入DOM所需的结构。
$(function() {
$("button#test").click(function() {
let l1 = $("li.level-one");
//get my list of first levels/
let l1txt = $.map(l1, function(elem) {
return $.trim($(elem).contents().first().text()).split(",");
});
//make the list unique
l1txt = l1txt.filter(function(item, pos, self) {
return self.indexOf(item) == pos;
});
//get the matching list-items
let objs = $.map(l1txt, function(t) {
return {
level1: t,
level2: findMatches(t)
};
});
//console.log(l1txt);
//console.log(objs);
//findMatches("flowers");
let $ul = $("<ul>"); //make the new ul to dump em in
$ul.append($.map(objs, function(elem) {
let $sub = $("<ul>").append(elem.level2); //these are the matched li's
return $("<li class='level-one'>") //my new first item
.append(elem.level1) //append the text 'category'
.append($sub); //append that sub-list I just created
})).insertBefore($(this)); //place this before my button I clicked.
});
});
//locates the matching list-items for the "category"
function findMatches(level1) {
//make sure we clone the list-items, so the old list can hang around untouched.
return $(`li.level-one:contains("${level1}") li.level-two`).clone().toArray();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='test'>go</button>
<ul>
<li class="level-one">
flowers,trees
<ul>
<li class="level-two">
gardening
</li>
</ul>
</li>
<li class="level-one">
flowers,trees
<ul>
<li class="level-two">
planting
</li>
</ul>
</li>
<li class="level-one">
orange,lemon
<ul>
<li class="level-two">
fruit
</li>
</ul>
</li>
<li class="level-one">
orange,lemon
<ul>
<li class="level-two">
citrus
</li>
</ul>
</li>
</ul>