这是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>
我通过指定单独的 ID 使用以下代码。
编辑
有一个 $(document).click
设置,如果用户当前在任何这些文本字段中输入任何内容,我会避免触发函数。一切正常。我的问题是,有没有办法将所有元素包含在父级中,而不是添加单独的元素作为目标?
$(document).click(function(e) {
if ($(e.target).closest("#tf1, #tf2, #tf3, #btn3").length) { //Can these individual elements be replaced by using parent div ID?
return;
}
if (typeof commonFunc == "function"){
commonFunc();
}
});
通过这样做,我不需要跟踪添加的新元素。
最佳答案
解决办法是
if($(e.target).closest("#parentDiv").children().length)
关于javascript - 通过父元素获取所有子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34016041/