防止jQueryUI中的重复项可排序 [英] prevent duplicated item in jQueryUI sortable
问题描述
我是尝试通过使用条件检查是否存在相同的内容,防止将重复的项目从 #sort
拖入#sort2
基于#sort2
中的标题属性的项目。如果有重复的话,它会在附加新的之前删除旧的
I was trying to prevent duplicated items from being dragged into #sort2
from #sort
by using a condition to check if there were identical items based on their title attributes in #sort2
. If there was a duplicated, it would remove the old one before appending the new one
$("#sort2").sortable({
receive: function (e, ui) {
var title = ui.item.attr('title');
var img = $('#sort2').find('img[title="'+title+'"]');
console.log(title);
if(img.length)
{
img.remove();
}
ui.sender.data('copied', true);
}
});
但我的尝试不起作用,它只是在被拖入任何项目后立即删除#SORT2
。谁能告诉我怎么做?
But my attempt didn't work, it just removes any item as soon as it is being dragged into #sort2
. Can anyone show me how to do that?
$("#sort").sortable({
connectWith: ".connectedSortable",
helper: function (e, li) {
this.copyHelper = li.clone().insertAfter(li);
$(this).data('copied', false);
return li.clone();
},
stop: function () {
var copied = $(this).data('copied');
if (!copied) {
this.copyHelper.remove();
}
this.copyHelper = null;
}
});
$("#sort2").sortable({
receive: function (e, ui) {
var title = ui.item.attr('title');
var img = $('#sort2').find('img[title="'+title+'"]');
console.log(title);
if(img.length)
{
img.remove();
}
ui.sender.data('copied', true);
}
});
$('#sort2').on('click','img',function(){
$(this).remove();
});
HTML:
<div class='connectedSortable' id='sort'>
<img title='AAA' src='http://upload.wikimedia.org/wikipedia/commons/7/7f/Wikipedia-logo-en.png'/>
<img title='BBB' src='http://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Wikisource-logo.svg/32px-Wikisource-logo.svg.png'/>
</div>
<div class='connectedSortable' id='sort2'></div>
推荐答案
我找到了解决方案。原始示例删除所有具有相同标题的图像,因此我的方法是使用 img.filter(:gt(0))。remove();
以删除第一个重复。
I found a solution. The original example removes all the images with the same title, so my method is use img.filter(":gt(0)").remove();
to remove just the first duplicated.
$("#sort").sortable({
connectWith: ".connectedSortable",
helper: function (e, li) {
this.copyHelper = li.clone().insertAfter(li);
$(this).data('copied', false);
return li.clone();
},
stop: function () {
var copied = $(this).data('copied');
if (!copied) {
this.copyHelper.remove();
}
this.copyHelper = null;
}
});
$("#sort2").sortable({
receive: function (e, ui) {
var title = ui.item.attr('title');
var img = $('#sort2').find('img[title="'+title+'"]');
console.log(title);
if(img.length)
{
img.filter(":gt(0)").remove();
}
ui.sender.data('copied', true);
}
});
$('#sort2').on('click','img',function(){
$(this).remove();
});
这篇关于防止jQueryUI中的重复项可排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!