Javascript 按其父元素获取所有子元素
这是div结构Javascript 按其父元素获取所有子元素,javascript,jquery,Javascript,Jquery,这是div结构 <div id="parentDiv"> <input type="text" id="tf1"> <input type="text" id="tf2"> <input type="text" id="tf3"> <button id="bt3">Text</button> </div> 通过这样做,我不需要跟踪添加的新元素 $(e.target).children() //
<div id="parentDiv">
<input type="text" id="tf1">
<input type="text" id="tf2">
<input type="text" id="tf3">
<button id="bt3">Text</button>
</div>
通过这样做,我不需要跟踪添加的新元素
$(e.target).children() // Will return all the children of whatever e.target is
编辑
$(document).click(function(e) {
if ($(e.target).children().length==0) {
// No children element.
return;
}
else{
// There are some child elements.
}
});
解决办法是
if($(e.target).closest("#parentDiv").children().length)
你的意思是像
$(e.target).children()
?你能清楚地解释你的需求吗?这意味着你的当前状态和预期输出是什么?这就是你想要的:$(e.target).最近的(#parentDiv”).children().length?。最近的()
会进入DOM树(类似于.parent()
)-若要向下获取子元素,只需更改为.children()
-无参数表示全部,或向筛选器添加参数。谢谢。我正在$(文档)中使用它。单击()
函数。如何添加$('#parentDiv').children()
?请参见我的编辑。我希望包含$('#parentDiv')
中的所有元素,而不必单独键入其中的所有元素。e、 g..closest(#tf1,#tf2,#tf3,#btn3”)。长度
请参见我编辑的答案。如果有帮助,请考虑向上投票并将其标记为正确答案。$(“#parentDiv”).children().length
为什么要在此处检查子项
长度,而您要选择该子项
中最接近的元素?查找任何最近的(“#parentDiv”)
意味着它必须有子级。
if($(e.target).closest("#parentDiv").children().length)