此代码在无序列表中从下到上删除重复的li。如何修改以从上到下删除重复的li?
function removeDuplicates(){
var map = {};
$("UL").find(".data").each(function() {
var value = $(this);
if (map[value.text()] == null){
map[value.text()] = true;
} else {
$(this).parent('li').remove();
}
});
}
如果上述示例无法解决问题,我们将不胜感激任何其他类型的高效代码示例。
答案 0 :(得分:2)
您可以尝试存储当前元素,然后删除前一个元素,如
function removeDuplicates() {
var map = {};
$("UL").find(".data").each(function () {
var value = $(this);
if (map[value.text()]) {
map[value.text()].parent('li').remove();
}
map[value.text()] = value;
});
}
演示:
function removeDuplicates() {
var map = {};
$("UL").find(".data").each(function() {
var value = $(this);
if (map[value.text()]) {
map[value.text()].parent('li').remove();
}
map[value.text()] = value;
});
}
removeDuplicates();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><span class="data">1</span></li>
<li><span class="data">2</span></li>
<li><span class="data">3</span></li>
<li><span class="data">2</span></li>
<li><span class="data">1</span></li>
<li><span class="data">4</span></li>
<li><span class="data">5</span></li>
<li><span class="data">2</span></li>
</ul>