Delegating Event Handling in jQuery: Direct vs. Delegated .on()
The jQuery .on() method allows for registering event handlers on DOM elements. Two distinct approaches to event handling are direct and delegated binding. The direct binding directly attaches event handlers to specific elements, while delegated binding allows event handling on elements that match a selector within a parent element.
The last sentence of the given paragraph regarding delegated event handlers states that jQuery "runs the handler for any elements...matching the selector." This refers to the event bubbling mechanism in DOM.
When a delegated event handler is attached to a parent element using .on() with a selector, events are handled not only on the selected elements but also on their descendants that match the selector. As the event bubbles up the DOM tree, jQuery checks if any elements along the path match the selector and triggers the handler if a match is found.
To illustrate the difference, consider the following examples:
$("div#target span.green").on("click", function() { alert($(this).attr("class") + " is clicked"); });
This directly binds the click handler to all elements with the green class within the #target div. Each of these elements will independently handle click events.
In contrast, the following uses delegated binding:
$("div#target").on("click", "span.green", function() { alert($(this).attr("class") + " is clicked"); });
Here, the click event handler is attached to the #target div, but the selector "event bubbling" to elements matching "green." This means that any future elements with the "green" class created within the #target div will also trigger the click handler.
Delegated binding is particularly useful when dynamically adding and removing elements from the page, as it ensures that new elements inherit the event handling behavior without requiring manual binding.
The above is the detailed content of Direct vs. Delegated Event Handling in jQuery: Which `.on()` Approach Should You Choose?. For more information, please follow other related articles on the PHP Chinese website!