这个问题与这个问题类似(但不完全相同): Count immediate child div elements using jQuery
我有一堆代表给不同人的圣诞礼物的列表。 举个例子,这是一份送给一个人的礼物 list 。请注意,可以添加新人
<ul id = "presents">
<li id = "person1" >
<ul id = "presentsforperson1">
<li id = "present1" >
<ul id = "present1info">
<li> Present 1 </li>
<li> A New Pair of Shoes </li>
<li> $19.99 </li>
</ul>
</li>
<!-- More presents for person 1 can be added here dynamically-->
</ul>
</li>
<!-- More people can be added here -->
</ul>
与发布的问题不同,我将对象 Presentsforperson1 放在名为 drop(可放置)的变量中。我想知道使用此变量查找 1 号人物(在本例中为 1)的礼物数量的正确语法是什么?
这是我迄今为止尝试过的:
var numberofPresents = $(drop + "ul > li").length; //drop holds li#presentsforperson1 .droppable
var numberofPresents = $(dropid + "ul > li").length; //dropID is $(drop).attr("id");
最佳答案
如果人员 ID 是包含其礼物的 ul
的 ID,则只需:
$('#personId > li').length
会做的。
更新
或者如果 id 位于变量中:
$('#' + personId).children('ul').length
您显然可以将子选择器附加到选择器字符串,例如:
$('#' + personId + ' > ul').length
但我个人认为带有 .children 调用的版本更具可读性。
关于javascript - 使用带有变量的 jquery 计算直接子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8577453/