Why would this work :
$(document).on(\"dblclick\", \"#areaA tr:has(td)\", function(e) {
//code here
});
and this does not
Is there really a difference between these two pieces of code?
Yes. The first piece of code is a form of delegated event handling where the handler is fired by events bubbling up the document that were triggered by descendant elements. The second is binding an event handler to the actual element returned by jQuery for the designated selector (in this case #areaA tr:has(td)
).
Here's the relevant information from the jQuery documentation:
First piece of code:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
Second piece of code:
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()
The main difference is that the condition in the first one will be checked each time you click. So if the element with id areaA
or the tr
or td
inside is added dynamically, only the first one can work.
The first method you describe works because you are selecting a static parent and then a dynamic child, which follows the rules of binding events to dynamically created elements with the .on method.
Here is the syntax for the .on
method, which it sounds like you have done a bit of studying on already.
$(selector).on(event,childSelector,data,function,map)
So if I want to bind to a dynamic element with .on
, I have to dollar sign select a static parent element first then, inside the .on
method, select the dynamic child element. In your case the correct use case would work like this:
$("body").on('dblclick', '#areaA tr:has(td)', function(e) {
//Code here
});
Since you mentioned it wasn't working I'm assuming #areaA
isn't a static element. You can replace body for a more relevant static element, or just leave it body, it doesn't really matter.