[英]Why is event.preventDefault() able to prevent default browser behavior for child element?
I understand that event.preventDefault()
can prevent browser default behavior, but why does it work if you put this on parent element's event handler?我知道event.preventDefault()
可以阻止浏览器的默认行为,但是如果你把它放在父元素的事件处理程序上它为什么会起作用?
Example:例子:
document.getElementById("parent").addEventListener('click', (e)=>{ alert('parent click'); //e.stopPropagation(); e.preventDefault(); }); document.getElementById("button").addEventListener('click', (e)=>{ alert('click'); //e.stopPropagation(); //e.preventDefault(); //return true; });
.foo{ background-color: red; text-align: center; padding: 16px; margin-bottom: 16px; }
<div id ="parent"> <a href="http://www.google.com" target="_blank"> <div id="button" class="foo" tabindex='-1'> hello </div> </a> </div>
If you click the button, there is no navigation.如果单击该按钮,则没有导航。 Why does it work?为什么有效?
Because that is the way how the DOM structure works.因为这就是 DOM 结构的工作方式。 In this case, the button is a part of the parent.在这种情况下,按钮是父级的一部分。 Therefore a click on the button is also a click on the parent, and therefore both onclicks will be triggered.因此,单击按钮也是对父级的单击,因此将触发两个 onclicks。 Note that the onclicks will be triggered from the bottom up, meaning the buttons event will be triggered first, after which it's parent gets triggered, after which the parent of the parent will get an onclick event and so on.请注意,onclicks 将自下而上触发,这意味着将首先触发按钮事件,然后触发它的父级事件,之后父级的父级将获得一个 onclick 事件,依此类推。
If this results in an unwanted result you can prevent this behavior by, as i think you already noticed, the event.stopPropagation()
function.如果这导致了不需要的结果,您可以通过event.stopPropagation()
函数来防止这种行为,正如我认为您已经注意到的那样。 If this method is called the event will not be triggered on the parents from that element upward.如果调用此方法,则不会在从该元素向上的父级上触发事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.