Direct vs. Delegated Event Handling with jQuery .on()
When utilizing the jQuery .on() method for event handling, there is a fundamental difference between direct and delegated event handlers.
Direct event handlers, as implied by their name, attach event listeners directly to specific elements. For example:
$("div#target span.green").on("click", function() { alert($(this).attr("class") + " is clicked"); });
In this scenario, the click event listener is directly bound to each span.green element within the div#target container.
Delegated event handlers, on the other hand, attach event listeners to a parent element and delegate the handling of events to descendant elements that match a selector. For instance:
$("div#target").on("click", "span.green", function() { alert($(this).attr("class") + " is clicked"); });
Here, the click event listener is attached to the div#target container, which then delegates the handling of clicks to any descendant span.green elements.
The key distinction is that in delegated event handling, the handler is not called if the event occurs directly on the parent element. Instead, the event bubbles up the DOM tree, and the handler is only invoked for descendant elements that match the provided selector. This can be beneficial for dynamic content where new elements may be added or removed, as the event listener will automatically apply to any matching descendants without the need for explicit binding.
In the provided example, both direct and delegated event handlers result in the same behavior because there are no dynamic elements added or removed. However, if new span.green elements were dynamically added to the page, only the delegated event handler would handle their click events.
The above is the detailed content of Direct vs. Delegated Event Handling in jQuery: When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!