javascript - 如何计算可排序 div 中的元素数量?

标签 javascript jquery html css jquery-ui-sortable

我在一个 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 中的元素数量?

最佳答案

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

找出#boxtop里面有多少元素你必须选择它的所有后代,然后检查 .length :

// All descendants:
$("#boxtop").find("*").length    // or:
$("#boxtop *").length

// Or count immediate children only:
$("#boxtop").children().length

在你的情况下,我认为检查直接 child 可能是你想要的。但不要像这样设置全局变量:

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

...因为这将设置 numChild到页面第一次打开时的长度,在用户开始与之交互之前。你需要检查 $("#boxtop").children().length$(".box1").children().length在需要值(value)的地方。

顺便说一句,您不需要三个独立的 $(document).ready(...)处理程序:将所有代码组合到一个准备就绪的处理程序中,或者如果您将 <script>主体末尾的元素,您根本不需要现成的处理程序。

关于javascript - 如何计算可排序 div 中的元素数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46966359/

相关文章:

jquery - 所有容器同时出来

html - 当用户最小化浏览器窗口时,如何使我的 CSS/HTML 类别菜单优雅地最小化?

javascript - 在一个事件中提交两个表单

javascript - 在音频文件播放一定时间之前,如何防止用户滚动到页面的一部分?

javascript - AngularJS SVG 路径指令

javascript - Express-handlebars 路由参数链接到同一页面

jQuery 在单击时显示 div,隐藏多个嵌套 div 中的其他内容

php - 我的 JQuery Chosen 插件不工作

javascript - Angular2 数据表的搜索/过滤组件

javascript - React/Preact .map 一个图标,点击后运行一个函数