javascript - 通过父元素获取所有子元素

标签 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>

我通过指定单独的 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/

相关文章:

javascript - 检测特定图像何时完成加载

javascript - if/else 语句 : Search through multiple possible values only finds last value (javascript)

javascript - if function with window.location.hash 帮助

javascript - Jquery 单选按钮逻辑

jquery - 如果我想让一个页面有一个主题滚动器(或多或少像 jQuery themeroller),它应该如何工作

jquery - Rails acts_as_votable ajax 不工作

javascript - 动态添加的复选框未模型绑定(bind)到 IList

javascript - 如何修复错误 : TypeError: elements. classList 未定义?

javascript - 如何在 React-Native 中转换这个对象?

javascript - .slideUp() 没有按预期工作