What is event bubbling?
Event bubbling is an event handler that automatically calls its parent element in the child element's event handler when the parent and child elements have the same event.
Demo
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/> <title>Event bubbling</title> <Scriptsrc= "Jquery-1.8.3.min.js"></Script> <Script> $(function () { $("#div"). Click (function () { $( This). Text ("I'm the div ."); }); $("#img"). Click (function () { $( This). Parent (). CSS ("Border", "1px solid Red"); }); }) </Script></Head><Body> <DivID= "Div"> <imgID= "img"src= "Images/gd.jpg" /> </Div></Body></HTML>
Interface effect when you click the img element under Div
With the above code we just want to make the div's border red when the mouse clicks on it and not delete the picture, but he automatically calls the parent element (DIV) When executing the child Element (IMG) event handler, which is event bubbling.
How do I cancel event bubbling?
Event bubbling can be manually canceled by the programmer, which means that the parent element is stopped in the event handler of the child element
Demo
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/> <title>Event bubbling</title> <Scriptsrc= "Jquery-1.8.3.min.js"></Script> <Script> $(function () { $("#div"). Click (function () { $( This). Text ("I'm the div ."); }); $("#img"). Click (function () { $( This). Parent (). CSS ("Border", "1px solid Red"); Event.stoppropagation ();
}); }) </Script></Head><Body> <DivID= "Div"> <imgID= "img"src= "Images/gd.jpg" /> </Div></Body></HTML>
Event bubbling can be canceled as shown in the code above
Demo
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/> <title>Event bubbling</title> <Scriptsrc= "Jquery-1.8.3.min.js"></Script> <Script> $(function () { $("#div"). Click (function () { if(Event.target==event.currenttarget) { $( This). Text ("I'm the div ."); } }); $("#img"). Click (function () { if(Event.target==event.currenttarget) { $( This). Parent (). CSS ("Border", "1px solid Red"); } }); }) </Script></Head><Body> <DivID= "Div"> <imgID= "img"src= "Images/gd.jpg" /> </Div></Body></HTML>
This method also solves the problem list and does not stop the event bubbling. He determines whether the triggering element of its event and the current element are the same element if the processing code is executed, and if it is not, the processing code is not executed, but the event is bubbling up until the BODY element
About event bubbling in jquery