JQuery With doubleclick event

Why does it work:

$(document).on("dblclick", "#areaA tr:has(td)", function(e) { //code here }); 

and it is not

 $("#areaA tr:has(td)").on('dblclick', function(e) { //Code here }); 

I exactly follow the example on the jquery documentation page, but my double click does not work. When I do this in the first way, it works, but it looks like it fires the event twice.

This applies to the Kendo user interface grid.

Is there a difference between the two code snippets?

+49
jquery
Nov 29
source share
3 answers

The main difference is that the condition in the first will be checked every time you click. Therefore, if an element with id areaA or tr or td inside is added dynamically, only the first one can work.

+39
Nov 29
source share

Is there a difference between the two code snippets?

Yes. The first piece of code is a form of delegated event processing in which the handler is triggered by events bubbling a document that were initiated by descendant elements. The second binds the event handler to the actual element returned by jQuery for the assigned selector (in this case #areaA tr:has(td) ).

Here is the relevant information from jQuery documentation:

The first piece of code:

Delegated events have the advantage that they can handle events from descendant elements that are added to the document at a later time. By choosing an element that is guaranteed to be present for the duration of the attached delegated event handler, you can use delegated events to avoid the need to attach and delete events often.

Second code snippet:

Event handlers are bound only to the currently selected elements; they must exist at the time your code calls the .on () call

+3
Apr 20 '16 at 15:29
source share

The first method you describe works because you select a static parent, and then a dynamic child that follows the rules for binding events to dynamically created elements using the .on method.

Here is the syntax of the .on method, which sounds like you have done a bit of work.

 $(selector).on(event,childSelector,data,function,map) 

So, if I want to bind to a dynamic element using .on , I must mean the dollar sign, first select the static parent element, and inside the .on method select the dynamic child element. In your case, the correct usage example will work as follows:

 $("body").on('dblclick', '#areaA tr:has(td)', function(e) { //Code here }); 

Since you mentioned that it does not work, I assume that #areaA not a static element. You can replace the body with a more important static element or just leave its body, it does not matter much.

+1
Jul 31 '17 at 13:39
source share



All Articles