1

这就是我想要实现的目标 - 我在一个可排序列表 ( #sortable2) 中有七个列表项,我将它们拖放到一个空的可排序列表 ( #sortable1) 中。

我想计算新的可排序列表 ( #sortable1) 中的元素数量,并显示一个警报,告诉用户当前的项目数量。我希望这也可以在删除项目时起作用。

这是我的 HTML:

    <ul id="sortable2" class="dropfalse">
       <li id="1">Section 1</li>
       <li id="2">Section 2</li>
       <li id="3">Section 3</li>
       <li id="4">Section 4</li>
       <li id="5">Section 5</li>
       <li id="6">Section 6</li>
       <li id="7">Section 7</li>
    </ul>

    <ul id="sortable1" class="droptrue">

</ul>

和 jQuery:

    $("#sortable1 li").each(function() {
        var elem = $(this);

        // I have just added one example here (if two added) for brevity

        if (elem.children("li").length = 2) {
            alert('There are two elements');
        }
});
4

3 回答 3

1

你需要drop在 droppable 的事件上运行它 - 假设 jQueryUI droppable,这样的事情会起作用:

$('#sortable1').droppable({
    drop: function(event, ui) {
        var liCount = $("#sortable1 li").length;
        // do something with liCount...
    }
});
于 2013-01-30T10:44:27.570 回答
0

2个主要问题是:

在计算元素数量时使用赋值而不是方程

计算 li 元素的子元素而不是 ul 元素的正确代码:

$("#sortable1").each(function() {
        var elem = $(this);

        // I have just added one example here (if two added) for brevity

        if (elem.children("li").length == 2) {
            alert('There are two elements');
        }
});
于 2013-01-30T10:45:13.287 回答
0

您应该使用receiveremove事件 - 如可排序 API中所述。

这是 jsfiddle 中的一个工作示例和示例代码:

function addRemoveHandler(event, ui) {
    alert("Number of items in sortable1: " + $(this).find("li").length);
}

$( "#sortable2" ).sortable({
    connectWith: "ul"
});
$( "#sortable1" ).sortable({
    connectWith: "ul",
    receive: addRemoveHandler,
    remove: addRemoveHandler
});
于 2013-01-30T10:59:01.173 回答