Home > Web Front-end > JS Tutorial > body text

Detailed introduction to controlling the execution order of binding events in JS

黄舟
Release: 2017-03-01 15:08:01
Original
1140 people have browsed it

In JS, the default execution time of bound events is in the bubbling phase, not in the capturing phase. This is why when both the parent class and the child class are bound to an event, the event bound to the child class will be called first, and then the event of the parent class will be called. Look directly at the following example




	
	
	

Copy after login

When the id3 element is clicked, the execution result is: id2, id3, id1

Analysis: Because the method bound by obj2 is executed in the capture phase, the events bound by obj1 and obj3 are executed in the bubbling phase.



##JS in By default, after the event is obtained, all the listening objects of the event are captured starting from the root element, and then executed one by one during the bubbling phase. We can specify whether the event is executed in the bubbling phase or the capturing phase when binding the event.

obj.addEventListener(event,function(){},bool)

##bool: false, represents execution in the bubbling phase

bool:true, represents the capture phase execution

Additional: Event bubbling

Prevent bubbling

w3c’s method is e.stopPropagation(), while IE uses e.cancelBubble = true;

Prevent default behavior

w3c method is e.preventDefault(), IE uses e .returnValue = false;

So in the appeal example, if we add prevent bubbling behavior for all events:

That is, the JS code in the appeal is changed to the following:

Copy after login
When id3 is clicked: Execution result: id2


When Click on id2: Execution result: id2


When click on id1: Execution result: id1


Through this example, we found that the event was prevented from bubbling and the event was prevented from continuing. Capture to the lower level.

The browser used for testing is: Google Chrome

Version 47.0.2526.106 m

## The above is the control binding in JS For a detailed introduction to the event execution sequence, please pay attention to the PHP Chinese website (m.sbmmt.com) for more related content!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!