【问题标题】:Changing a div's class based on the number of elements dropped into a sortable list根据放入可排序列表的元素数量更改 div 的类
【发布时间】:2013-01-30 10:41:57
【问题描述】:

这就是我想要实现的目标 - 我在一个可排序列表 (#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');
        }
});

【问题讨论】:

    标签: jquery draggable jquery-ui-sortable content-length


    【解决方案1】:

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

    $('#sortable1').droppable({
        drop: function(event, ui) {
            var liCount = $("#sortable1 li").length;
            // do something with liCount...
        }
    });
    

    【讨论】:

    • 你没有发现明显的失败
    • @Blacksonic 我做了 - 但他目前使用的方法是完全错误的,因为它将 1) 仅在加载时运行,而不是在删除后 2) 在现有 @987654324 中查找子 li 元素@元素。
    • @MartinSmith 没问题,很乐意提供帮助。
    【解决方案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');
            }
    });
    

    【讨论】:

      【解决方案3】:

      您应该使用receiveremove 事件 - 如Sortable API 中所述。

      Here's a working example in 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
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-27
        • 2017-04-18
        • 1970-01-01
        • 2020-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多