简体   繁体   English

防止来自子元素的事件默认值

[英]preventing event default of from child element

How to prevent parent event if child's event is executed. 如果执行子事件,如何防止父事件。 Here is the code see the comments 这是代码,请参阅注释

document.addEventListener('touchend', function (e) { 
    //Do something here
}, false);

someChildElement.addEventListener('touchend', function (e) { 
    //Do something here

    //if this code block is executed then do-not execute the touchend event of document//
}, false);

You can try this in your child event handler 您可以在您的子事件处理程序中尝试

event.stopPropagation()

For Internet Explorer, you should use 对于Internet Explorer,您应该使用

window.event.cancelBubble = true

Have you tried changing the event propagation mechanism? 您是否尝试过更改事件传播机制?

The last parameter in the 'addEventListener' method controls the propagation of event. “ addEventListener”方法中的最后一个参数控制事件的传播。 If we set it to false, the event bubbles but if we set it to true, the event is captured and then it bubbles up. 如果将其设置为false,则事件冒泡,但如果将其设置为true,则捕获事件,然后冒泡。 So when we set it to 'true', the "container" receives the event before the "child" and when we set it to 'false', the child receives the event ahead of the container. 因此,当我们将其设置为“ true”时,“容器”在“ child”之前接收事件,而当我们将其设置为“ false”时,child在容器之前接收事件。 In simple words, when we set the parameter to 'false', the event registrar starts from inner element as the event bubbles from 'child' element to its container element. 简而言之,当我们将参数设置为“ false”时,事件注册器从内部元素开始,因为事件从“ child”元素冒泡到其容器元素。 And when we set it to 'true', the event registrar first travel downwards to the container element as it is the first element to which the event is registered, traversing the document tree from outermost element and then it reaches to the child element. 当我们将其设置为“ true”时,事件注册器首先向下移动到容器元素,因为它是向其注册事件的第一个元素,从最外面的元素遍历文档树,然后到达子元素。

And then you can use event.stopPropagation to stop event from traversing further. 然后,您可以使用event.stopPropagation阻止事件进一步遍历。

You can learn more about it here on MDN 您可以在MDN上了解更多信息

Use 采用

preventdefault(event) function. preventdefault(event)函数。

http://api.jquery.com/category/events/event-object/ http://api.jquery.com/category/events/event-object/

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

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