What is the purpose of the selector
in the jQuery on()
method?
In what situation is
$("#fish").on("click", ".button", function() {
// something
});
better than, say,
$("#fish").find(".button").on("click", function() {
// something
});
?
I've looked on the jQuery documention and found:
If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
Am I correct in saying that the difference is that in my first example, the event is bound to the #fish
, but only listens for events bubbling up from the .buttons
, whereas in the second example the event is bound to each of the .buttons
? If so what are the implications of this? :S
So if the event is bound to the #fish, when you click a .button, is there anyway to know which .button was clicked on? this will refer to the #fish rather than the .button, correct?