event.preventDefault vs event.stopPropagation [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-11-28 06:29:23

I am not a Javascript expert but as far as I know:

stopPropagation is used to make sure the event doesn't bubble up the chain. eg. a click on a <td> tag would also fire click events on it's parent <tr>, and then its parent <table>, etc. stopPropagation prevents this from happening.

preventDefault is used to stop the normal action of an element, eg. preventDefault in a click handler on a link would stop the link being followed, or on a submit button would stop the form being submitted.

  • stopPropagation on a child will stop that event from happening on the parent (the entire ancestors)
  • preventDefault on a child will stop the event on the child but it will happen on it's parent (and the ancestors too!)

Now in your code which is the parent? which is the child? img is child tr is parent(well grandparent to be honest), So guess where the stopPropagation code should be.

Event preventDefault From W3C:

The event.preventDefault() method stops the default action of an element from happening. For example:

Prevent a submit button from submitting a form Prevent a link from following the URL

Event stopPropagation From W3C:

The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!