prevent duplicated item in jQueryUI sortable

2020-04-12 07:27发布

Fiddle Example

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);
    }
});

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>

1条回答
一夜七次
2楼-- · 2020-04-12 08:00

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.

Example

$("#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();
});   
查看更多
登录 后发表回答