【问题标题】:How do I count the number of elements in a sortable div?如何计算可排序 div 中的元素数量?
【发布时间】:2017-10-27 01:53:34
【问题描述】:

我在一个 HTML 文档中有多个 div,其中包含可以相互排序的较小 div。加载文档时,这些较小的 div 的随机数量会附加到 #boxtop。

这是我的 HTML:

<html>
<body>
<head>
    <title></title>
    <script link src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link rel="stylesheet" href="jquery-ui.min.css">
    <link rel = "stylesheet" type" type="text/css" href = "style.css">
    <script src="jquery-ui.min.js"></script>
    <div id = "boxtop" class = "dragInto"></div>
    <button type="button" id="button">My Children!!!</button>
    <div id = "eqbox"></div>
    <div id = "box1" class = "ansBox"></div>
    <div id = "box2" class = "ansBox"></div>
    <div id = "box3" class = "ansBox"></div>
</head>
</body>
</html>

这是我的相关 jQuery

$(document).ready(function()
{
    $("#boxtop").sortable
    ({
        connectWith: ".ansBox"          
    });

    $(".ansBox").sortable
    ({
        connectWith: ".ansBox"          
    });

});

$(document).ready(function()
{
    $("dragInto").droppable
    ({
        accept: ".box"
    });
});

var numChild = $("#boxtop").length;
$(document).ready(function()
{
    $("#button").click(function() 
    {
        console.log(numChild);
    });
});

我的问题是:如何获取已排序 div 中的元素数量。我目前尝试使用 numChild 将该值打印到控制台,但打印的是“1”。如果我将一堆元素从#boxtop 拖到.box1,我怎么能得到.box1 中的元素数量?

【问题讨论】:

    标签: javascript jquery html css jquery-ui-sortable


    【解决方案1】:

    .length 属性告诉您有多少元素属于您调用它的 jQuery 对象。因此,鉴于$("#boxtop") 匹配一个元素,$("#boxtop").length 将为 1。

    要找出#boxtop 中有多少元素,您必须选择它的所有后代并然后检查.length

    // All descendants:
    $("#boxtop").find("*").length    // or:
    $("#boxtop *").length
    
    // Or count immediate children only:
    $("#boxtop").children().length
    

    在您的情况下,我认为检查直系子女可能是您想要的。但不要设置全局变量,例如:

    var numChild = $("#boxtop").children().length;
    

    ...因为这会将numChild 设置为页面首次打开时的长度,在用户开始与之交互之前。您需要在需要该值的位置检查$("#boxtop").children().length$(".box1").children().length

    顺便说一句,您不需要三个单独的 $(document).ready(...) 处理程序:将所有代码组合到一个准备好的处理程序中,或者如果您将 &lt;script&gt; 元素放在不需要的正文末尾一个就绪的处理程序。

    【讨论】:

    • 感谢您的回复。现在按预期工作。非常感谢:)
    【解决方案2】:

    您需要从 sortable 实例中捕获 updatestop 事件。详细的文档就在那儿

    Live Demo And Working Code

    【讨论】:

      猜你喜欢
      • 2021-03-27
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多