Home >Web Front-end >JS Tutorial >Direct vs. Delegated Event Handling in jQuery .on(): Which Approach Should You Choose?
Direct vs. Delegated Event Handling in jQuery .on()
jQuery's .on() method provides two distinct event handling approaches: direct and delegated. The difference lies in the scope of event handling.
Direct Event Handling
In direct event handling, the event handler is bound directly to the target element. This means that the handler is only executed when the event occurs directly on that element, not on any of its descendants. For example:
$("div#target span.green").on("click", function() { alert($(this).attr("class") + " is clicked"); });
Delegated Event Handling
In delegated event handling, the event handler is bound to an ancestor element, and the selector specifies the descendant elements that should trigger the handler. This allows the handler to handle events that occur anywhere within the specified scope. For example:
$("div#target").on("click", "span.green", function() { alert($(this).attr("class") + " is clicked"); });
The key distinction is that in case 1, each span is directly responsible for handling its own events. In case 2, the container element (div#target) is delegated the responsibility of handling events for its child elements (span.green).
Example Comparison
The example provided demonstrates the differences between direct and delegated event handling in the context of clicking green spans within a div#target. Both methods achieve the same behavior of alerting the clicked span's class.
Direct Approach:
Delegated Approach:
The above is the detailed content of Direct vs. Delegated Event Handling in jQuery .on(): Which Approach Should You Choose?. For more information, please follow other related articles on the PHP Chinese website!