我有两个无序列表。一个无序列表动态填充,双击它的项目以添加到另一个无序列表。
我正在试图弄清楚如何检测动态填充列表中的项目是否已经在另一个列表中。如果是。然后它不应该再次添加。不想添加重复的项目。
填充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。
答案 0 :(得分:0)
if
声明中有几个问题。
this
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();
}