Analysis of JavaScript event Delegate usage and javascript event usage
This example describes how to use JavaScript event delegation. Share it with you for your reference. The specific analysis is as follows:
1. Click any part of the page to trigger the event
Create a script1.js file.
Copy codeThe Code is as follows: (function (){
EventUtility. addEvent (document, "click", function (evt ){
Alert ('hello ');
});
}());
Page section.
Copy codeThe Code is as follows: <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> </title>
</Head>
<Body>
<Script src = "eventUtility. js"> </script>
<Script src = "script1.js"> </script>
</Body>
</Html>
Output result: a dialog box is displayed when you click anywhere on the page.
However, we sometimes want to click an element in the document to trigger the event.
Ii. Use a delegate to trigger an event
Add a label to the page.
Copy codeThe Code is as follows: <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> </title>
</Head>
<Body>
<Div>
<P> <a href = "#"> click me </a> </p>
</Div>
<Script src = "eventUtility. js"> </script>
<Script src = "script1.js"> </script>
</Body>
Modify script1.js:
Copy codeThe Code is as follows: (function (){
EventUtility. addEvent (document, "click", function (evt ){
// Obtain the click object
Var target = eventUtility. getTarget (evt );
// Obtain the tag Name of the click object
Var tagName = target. tagName;
// If the tag is
If (tagName = ""){
Alert ("Click me ");
// Block the default link Behavior
EventUtility. preventDefault (evt );
}
});
}());
Output result: only the tab on the page is clicked.
The preceding advantages: no matter how many a tag elements are added to the document, all a tags have the ability to be triggered. This method is event Delegate. We want to register an event for the child element, but first register the event to the parent element of the child element. In this way, events are registered within the parent element, dynamically added, and any element similar to the child element.
If we register an event to a child element and dynamically add elements of the same type as the child element in the document, we must register events for these newly added child elements.
In addition, event delegation makes good use of "event bubbling ". When a child element is clicked, the child element captures the Click Event Based on "event bubbling" and triggers its own method.
I hope this article will help you design javascript programs.