在无序列表中查找重复项

Find duplicate item in unordered list

本文关键字:查找 无序 列表      更新时间:2023-09-26

我有两个无序的列表。一个无序列表被动态填充,然后双击它的项目添加到另一个无序的列表中。

我正试图弄清楚如何检测动态填充列表中的项目是否已经在另一个列表中。如果是,则不应再次添加。不希望添加重复的项目。

填充ul:的代码

.done(function(html) {
        var results = jQuery.parseJSON(html);
        $('#store_sel').children().remove();
            for (var i = 0; i <= results.length; i++){
                $("#store_selection").append("<li class='" + results[i].name + " stores'" + "id= " + results[i].uuid + 
                + ">" + results[i].name + "</li>");
        }      
    });

事件:

$('#store_selection').on('dblclick', 'li', function(e) {
    e.stopPropagation();
    e.preventDefault();
    if ($('#store_selected').find($(this))) {
        console.log('item already there');
    } else {
        $('#store_selected').append($(this).clone());
        //$(this).remove();
    }       
});

编辑:为什么不起作用?即使ul为空,它基本上也会转到console.log。

if语句中存在几个问题。

  1. 一个元素不能同时位于两个位置。因此在两个列表中找不到this
  2. 一个物体永远是真实的。请改用返回的选择器集合的length

由于ID在页面中必须是唯一的,我建议您使用data-属性来存储UUID

<li data-uuid="xxxx-yyy">

然后当你搜索时:

var uuid = $(this).data('uuid')
if ($('#store_selected').find('.stores[data-uuid='+uuid+']').length) {
    console.log('item already there');
} else {
    $('#store_selected').append($(this).clone());
    //$(this).remove();
}