我在一个 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/