在事件气泡中检测元素

Detect an Element in event bubbles

我有这个 html 代码:

<div class="container">
   <div class="parent">
     <!-- P Element Completely On Parent -->
     
     <p style="width: 100%; height: 100%;">Hello</p>
   
     </div>
   ........
</div>

这是我的 Javascript:

document.querySelector(".container").addEventListener("click", (e) => {
 
  if ( e.target == document.querySelector(".parent") ) {
    
     alert(" It Worked!!! ")
  
  }

}, 
true // <--- bubbling
)

Is it possible to detect parent elements clicking without giving event to it ( with event bubbling ) ?

The result code should work after client clicking on p element

是的,你可以试试这个

document.querySelector(".container").addEventListener("click", (e) => {
  
  var parentel = e.target.parentElement

  if (parentel.className == "parent") {

    alert(" It Worked!!! ")
  }
})
<div class="container">
  <div class="parent">
    <!-- P Element Completely On Parent -->

    <p class- "child" style="width: 100%; height: 100%;">Hello</p>

  </div>
</div>

如果 .parent 的嵌套是动态的,您可能需要从 currentTarget to the target 确定路径。然后在路径中搜索您要查找的特定元素。

// Determines the node path from baseNode to targetNode, by travelling up from
// the targetNode. The retuned array will include both the baseNode and the
// targetNode. If the targetNode is the baseNode an array with one elment is
// returned. Throws an error if baseNode is not an ancestor of targetNode.
function nodePath(baseNode, targetNode, currentPath = []) {
  currentPath.unshift(targetNode);
  if (targetNode == baseNode) return currentPath;
  return nodePath(baseNode, targetNode.parentNode, currentPath);
}

document
.querySelector(".container")
.addEventListener("click", ({currentTarget, target}) => {
  const path   = nodePath(currentTarget, target);
  const parent = path.find(node => node.matches(".parent"));

  if (parent) {
    console.log("It Worked!");
  }
});
<div class="container">
   <div class="parent">
     <!-- P Element Completely On Parent -->
     
     <p style="width: 100%; height: 100%;">Hello</p>
   
     </div>
   ........
</div>