简体   繁体   English

冒泡触发父项的点击事件

[英]trigger click event on parent with bubbling

I want to manually fire a click event on a parent container with dispatchEvent . 我想使用dispatchEvent在父容器上手动触发click事件。 The event bubbling does not seem to work. 事件冒泡似乎不起作用。

// trigger click event on parent container
parent.dispatchEvent(new MouseEvent("click", {
    bubbles: true,
    cancelable: true,
    view: window,
    clientX: 4,
    clientY: 4
}));

... ...

child.addEventListener('click', function(e) {
    alert('click')
}, false);

See this fiddle: 看到这个小提琴:

https://jsfiddle.net/o4j0cjyp/2/ https://jsfiddle.net/o4j0cjyp/2/

Events bubble up or not at all. 事件起泡或根本没有起泡。 The only way I know to bubble down would be to get all the elements in the targeted element, and iterate over the collection dispatching an event on all of them, some of them, or whatever your situation needs. 我知道失败的唯一方法是获取目标元素中的所有元素,并遍历集合,从而在所有元素,某些元素或您需要的任何情况下调度事件。 This could be bad as if you do not tell the event not to bubble you could easily end up in a infinite loop. 这可能很糟糕,就像您不告诉事件不要冒泡一样,您很容易陷入无限循环。

A better way to go about your goal is to use event delegation, where you use a common parent as the event listener element. 实现目标的更好方法是使用事件委托,在事件委托中,将公共父对象用作事件侦听器元素。 Then when the event happens check the event target, if it is one you want than do whatever work. 然后,当事件发生时,检查事件目标,如果目标是目标,则不要执行任何工作。

So for your html 因此,对于您的html

<div id="parent-container">
  <div id="child-container">
    this area has a click listener
  </div>
</div>
<div id="click-info">No 'click' event yet.</div>
<div class="btn" id="trigger-parent-btn">
  trigger 'click' event on parent container<br>
  [ does not work ]
</div>
<div class="btn" id="trigger-child-btn">
  trigger 'click' event directly on child container
</div>

Instead of setting up event listeners on each one, and trying to trigger a child or parent event, we can setup a click listener on a common parent (in this case <body> ). 无需在每个事件监听器上都设置事件监听器,而是尝试触发子事件或父事件,我们可以在公共父对象(在本例中为<body> )上设置单击监听器。 In there we can test if the target element is one of the three we want to trigger showing click info, if so do show the info. 在这里,我们可以测试目标元素是否是我们要触发的显示点击信息的三个元素之一,如果需要,则显示信息。

 var info = document.querySelector("#click-info"); document.body.addEventListener("click",function(event){ var target = event.target; if(target.classList.contains("btn") || target.id=="child-container"){ info.innerHTML = 'Clicked at ' + event.clientX + ':' + event.clientY; } }) 
 <div id="parent-container"> <div id="child-container"> this area has a click listener </div> </div> <div id="click-info">No 'click' event yet.</div> <div class="btn" id="trigger-parent-btn"> trigger 'click' event on parent container<br> [ does not work ] </div> <div class="btn" id="trigger-child-btn"> trigger 'click' event directly on child container </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM