我有两个无序列表。一个无序列表会动态填充,您双击它的项目即可将其添加到另一个无序列表中。
我试图找出如何检测动态填充列表中的项目是否尚未在其他列表中。如果是。那么它不应该再次添加。不想添加重复的项目。
填充 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
语句中有几个问题。
- 一个元素不能同时出现在 2 个位置。因此,您无法在 2 个列表中找到
this
- 对象总是返回 true。使用返回的选择器集合的
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();
}
关于javascript - 在无序列表中查找重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26713110/