在窗口单击事件中访问元素及其子代/后代

时间:2018-11-05 15:26:28

标签: javascript events

在我的窗口事件中,如果指针单击父项或其子项/后代,则它应该执行某些操作。 问题是该事件无法访问父母的孩子和孙子。条件存储在targetIsInsideParent变量中。

HTML

<div class="parent">
  Parent
  <div class="child">
    Child
    <div class="grandchild">
      GrandChild
    </div>
  </div>
</div>

JS

const parent = document.querySelector('.parent');

window.addEventListener('click', e => {
  const targetIsParent = e.target === parent;
  const targetIsInsideParent = e.target === parent.children; // !!!!

  if(targetIsParent || targetIsInsideParent) {
    console.log('Good');
  }
})

1 个答案:

答案 0 :(得分:1)

尝试使用parent.contains(e.target)parent.compareDocumentPosition(e.target) === 20

const parent = document.querySelector('.parent');

window.addEventListener('click', e => {
  const targetIsParent = e.target === parent;
  const targetIsInsideParent = parent.contains(e.target);
  // const targetIsInsideParent = parent.compareDocumentPosition(e.target) === 20; // alternative, but also works good
  if(targetIsParent || targetIsInsideParent) {
    console.log('Good');
  }
})
<div class="parent">
  Parent
  <div class="child">
    Child
    <div class="grandchild">
      GrandChild
    </div>
  </div>
</div>
<div>Other</div>