在无序列表中查找重复项

时间:2014-11-03 11:18:04

标签: javascript jquery ajax

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

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

填充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。

1 个答案:

答案 0 :(得分:0)

if声明中有几个问题。

  1. 元素不能同时在2个地方。因此,您无法在2个列表中找到this
  2. 一个对象总会返回真实状态。请使用返回的选择器集合的length
  3. 由于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();
    }