The js block default event shares the js block event bubble example with the js block event bubble

  • 2020-03-30 01:34:19
  • OfStack

1. The event. The preventDefault ();   - prevents default events for elements.
Note: the default event of click jump of element a,

Default events for form elements such as button, radio,

There is no default event for the div element

Ex. :


<a href="http://www.baidu.com" target="_black"> baidu </a>


var samp = document.getElementByTagName("a");
samp.addEventListener("click",function(e){e.preventDefault()},false);

Explanation: click the link when the normal situation will happen jump, but now we blocked its default event, namely jump event, then will not jump to baidu.


2. The event. StopPropagation ();   - prevents element bubbling events

Note: nested elements typically have bubbling events that can have some impact

Ex. :


<div id="c1" onclick="alert(1)">
<div id="c2" onlick="alert(2)">
<input type="button" id="c3" value=" Click on the " onclick="alert(3)">
</div>
</div>

Here by clicking on the button, the browser will successively pop-up 3, 2, 1, originally just wanted to let binding events on the button, but accidentally triggered the events on its two parent, here we just do a simple test, imagine if, in the project development to some buttons and his parent binding the important event at the same time, then the result will be disastrous. The solution is to stop the bubbling event.

Register the click event for the input while preventing it from bubbling


document.getElementById('c3').addEventListener('click',function(e){e.stopPropagation()},false);

OK!!!!!! the

  PS: here again for you to recommend an online query tool about JS events, summed up the common JS event types and functions:

Javascript events and function description:

(link: http://tools.jb51.net/table/javascript_event)


Related articles: