我在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
就您而言,我认为检查直系子女可能是您想要的。但不要设置全局变量,例如:
var numChild = $("#boxtop").children().length;
。因为这会将numChild
设置为页面首次打开时的长度,在用户开始与之交互之前。您需要在需要该值的位置检查$("#boxtop").children().length
或$(".box1").children().length
。
顺便说一句,您不需要三个单独的$(document).ready(...)
处理程序:将所有代码合并到一个就绪处理程序中,或者如果您将 <script>
元素放在正文的末尾,则根本不需要就绪处理程序。
从实例中捕获update
或stop
事件sortable
。详细的文档就在那里
- https://api.jqueryui.com/sortable/#event-stop
- https://api.jqueryui.com/sortable/#event-update
现场演示和工作代码