I have a dynamically generated navigation structure shown. Each location has storetypes generated from the stores at the location.
I need to remove duplicates per location so that groceries can appear in both locations. I tried the common jquery solution below which removes duplicates but it results in each storetype appearing only in one location.
var seen = {};
$("ul#storetypes").find("li").each(function(index, html_obj) {
txt = $(this).text().toLowerCase();
if (seen[txt]) {
$(this).remove();
} else {
seen[txt] = true;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
<li>Location 1
<ul id="storetypes" class="sub-menu">
<li>groceries</li>
<li>cakes</li>
<li>motor spares</li>
<li>groceries</li>
</ul>
</li>
<li>Location 2
<ul class="sub-menu">
<li>groceries</li>
<li>motor spares</li>
<li>motor spares</li>
<li>groceries</li>
</ul>
</li>
</ul>
3条答案
按热度按时间i7uq4tfw1#
您可以这样做:
这将查看每个
.sub-menu
,并查看是否已经存在具有相同文本的'li',并删除重复的。第一次
kcugc4gi2#
您所做是正确的,但只需对每个
<ul>
执行此操作。第一个
wxclj1h53#
您只需要在每个子列表中定位顶层迭代。
然后迭代其子项并删除重复项。
此外,您不需要jQuery。
第一个