Home  >  Article  >  Web Front-end  >  JavaScript event delegation usage analysis_javascript skills

JavaScript event delegation usage analysis_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:18:111086browse

The examples in this article describe the usage of JavaScript event delegation. Share it with everyone for your reference. The specific analysis is as follows:

1. Click any part of the page to trigger an event

Create a script1.js file.

Copy code The code is as follows:
(function() {
EventUtility.addEvent(document, "click", function(evt) {
alert('hello');
});
}());

Page section.

Copy code The code is as follows:





 




Output results: Clicking anywhere on the page will pop up a box.

However, sometimes we want to click on an element within the document to trigger an event.

2. Use delegation to trigger events

Add a tag to the page.

Copy code The code is as follows:





 

                                                                                                                                   




Modify script1.js to:


Copy code The code is as follows:
(function() {
EventUtility.addEvent(document, "click", function(evt) {
//Get the click object
        var target = eventUtility.getTarget(evt);
//Get the tag name of the clicked object
        var tagName = target.tagName;
​​​​ //If tag is a
If (tagName === "A") {
alert("click me");
//Default behavior of blocking links
              eventUtility.preventDefault(evt);
}
});
}());
Output result: Only when the a tag on the page is clicked will the box pop up.
The advantage of the above is: no matter how many a tag elements are added to the document, all a tags have the ability to be triggered. An approach like this is event delegation. We want to register events for child elements, but first register the event on the parent element of the child element. In this way, any dynamically added elements of the same type as the child element within the parent element are registered for the event.

If we register events to sub-elements, and then dynamically add elements of the same type as sub-elements in the document, we must register events for these newly dynamically added sub-elements.

In addition, event delegation makes good use of "event bubbling". When a child element is clicked, according to "event bubbling", the parent element of the child element captures the click event and triggers its own method.

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
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