jQuery drag and drop - Allow only one item in list

ぃ、小莉子 提交于 2019-12-22 11:02:19

问题


I work with this example from jQuery UI Sortable

I have a problem with drag and drop.
Table number 3 - sortable3 should only be able to receive one item.

This is my HTML

<div class="demo">

<ul id="sortable1" class='droptrue'>
    <li class="ui-state-default">Can be dropped..</li>
    <li class="ui-state-default">..on an empty list</li>
    <li class="ui-state-default">Item 3</li>
    <li class="ui-state-default">Item 4</li>
    <li class="ui-state-default">Item 5</li>
</ul>

<ul id="sortable2" class='dropfalse'>
    <li class="ui-state-highlight">Cannot be dropped..</li>
    <li class="ui-state-highlight">..on an empty list</li>
    <li class="ui-state-highlight">Item 3</li>
    <li class="ui-state-highlight">Item 4</li>
    <li class="ui-state-highlight">Item 5</li>
</ul>

<ul id="sortable3" class='droptrue'>
</ul>

My CSS

#sortable1, #sortable2, #sortable3{
    list-style-type: none; 
    margin: 0; 
    padding: 0; 
    float: left; 
    margin-right: 10px; 
    background: #eee; 
    padding: 5px; 
    width: 143px;
}

#sortable1 li, #sortable2 li, #sortable3 li{
    margin: 5px; 
    padding: 5px; 
    font-size: 1.2em; 
    width: 120px; 
}

My Script

$(function() {
    $("ul.droptrue").sortable({
        connectWith: "ul"
    });

    $("ul.dropfalse").sortable({
        connectWith: "ul",
        dropOnEmpty: false
    });

    $("#sortable1, #sortable2, #sortable3").disableSelection();
});​

回答1:


To prevent any additional items from being dropped into sortable3, cancel the drop if the maximum number has been exceeded.

The code below is your current code, I only added the last method which attaches the received event to the third sortable.

$(function() {
    $("ul.droptrue").sortable({
        connectWith: "ul",
    });

    $("ul.dropfalse").sortable({
        connectWith: "ul",
        dropOnEmpty: false
    });

    $("#sortable1, #sortable2, #sortable3").disableSelection();

    $("#sortable3").on("sortreceive", function(event, ui) {
        var $list = $(this);

        if ($list.children().length > 1) {
            $(ui.sender).sortable('cancel');
        }
    });
});​

DEMO​



来源:https://stackoverflow.com/questions/12543248/jquery-drag-and-drop-allow-only-one-item-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!