1, event bubbling
<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
When you click on the internal <span> elements, it triggers your own and outer <div> and <body> click events, which is caused by event bubbling. Events propagate up and down the DOM hierarchy.
Event bubbling can cause unexpected effects, and sometimes it is necessary to block the bubbling behavior of the event, using the Stoppropagation () method to implement it.
To modify the Click event function for the <span> element:
Bind Click event $ ("
span") for <span> element. Click (function (event) { //Add an Event object parameter
$ ("#msg") to the method. HTML ($ ("#msg "). HTML () +" <p> layers span element clicked </p> ");
Event.stoppropagation (); Block <span> Click event Bubbling
});
When you click on the internal <span> element, it will only trigger its own Click event and will not bubble up again.
2. Block default behavior
JQuery provides a preventdefault () method to implement when a user's actions do not meet certain conditions and need to block the default behavior of certain elements, such as linked jumps and form submissions.
Block form submission When user does not fill in user name:
<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
If you want to block event bubbling and blocking element default behavior at the same time, you can return false in the event function instead of invoking the stoppropagation () and Preventdefault () methods.
Such as:
$ (": Submit"). Click (Function (event) {// Add an Event object parameter to the method
//When the user name is not entered, prompt and block the submit
if ($ (": Text"). val () = "") {
$ ("#msg"). Text ("User name cannot be empty");
return false; Prevents the default behavior of the Submit button (submit form) and event bubbling
}
}); $ ("span"). Click (Function (event) { //Add an Event object parameter
$ ("#msg") to the method. html ($ ("#msg"). HTML () + "<p> layers span element clicked </p>");
return false; Block <span> Click event bubbling and default behavior (this element has no default behavior)
});
This article on jquery in the event bubbling and blocking the default behavior is small series to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud-dwelling community.