What is event delegation

The so-called event delegation is to delegate the things that one should do to others. By using the principle of bubbling, the event is added to the parent element to trigger the effect of execution

Benefits:

  • To improve performance
  • Newly added elements can also execute previous events

How do I block the default action

Some HTML elements have default behaviors. For example, when clicking a tag, it will jump, and when clicking Submit in the form form, it will submit the form and jump. In order to prevent this default behavior of browser, JS provides corresponding methods

var $a = document.getElementsByTagName("a")[0]; $a.onclick = function(e){alert(" ") e.preventDefault(); //return false; // can also}Copy the code

When e.preventDefault() is used, the default behavior of the event is blocked

Return false is different from e.preventDefault(). It is only in HTML event attributes and DOM0-level event handlers that the default behavior of the event host is organized by returning return false.

How do I stop events from bubbling up

Without further ado, get right to the code

Function stopBubble(e){if(e &&e.topPropagation){// IE e.topPropagation (); } else{//IE window.event.cancelBubble=true; }}Copy the code

If not IE, directly with e.s topPropagation (), if is Internet explorer, with Windows. The event. The cancelBubble = true