This article describes the usage of JavaScript event delegation. Share it for your reference. The specific analysis is as follows:
1. Click on any part of the page to trigger the event
Create a script1.js file.
Copy the code as follows:(function() {
eventUtility.addEvent(document, "click", function(evt) {
alert('hello');
});
}());
Page section.
Copy the code as follows: <head>
<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: Clicking on any one of the page will pop up.
However, sometimes we want to click on an element in the document to trigger an event.
2. Use delegate to trigger events
Add a tag to the page.
Copy the code as follows: <head>
<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 to:
Copy the code as follows:(function() {
eventUtility.addEvent(document, "click", function(evt) {
//Get the click object
var target = eventUtility.getTarget(evt);
//Get the tag name of the click object
var tagName = target.tagName;
//If tag is a
if (tagName === "A") {
alert("Click me");
//Block the default behavior of links
eventUtility.preventDefault(evt);
}
});
}());
Output result: The box will pop up only if you click the a tag on the page.
The above benefits are: no matter how many a tag elements are added to the document, all a tags have the ability to be triggered. This is the commissioning of the event. We want to register events for child elements, but we first register events with the parent element of the child element. In this way, any element that is dynamically added and of the same type as the child element will be registered within the parent element.
If we register events to child elements and dynamically add elements of the same type as the child elements in the document, we must register events for these child elements that have just been added dynamically.
In addition, event delegation makes good use of "event bubbles". When clicking on a child element, according to "Event Bubble", 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.