0

I know that this question has been asked before,but unfortunately those didn't seem to solve my issue. I have a <table> and i have to add dblclick event to each of those,but i also am adding rows to the table using AJAX(after page load).

I have got it working but have posted 2 codes,one worked and other didn't.

a)This code works for me:

$(document).on("dblclick","td",function(){ 
   //THIS WORKS FOR ELEMNTS ADDED AFTER PAGE LOAD
});

b)This code i tried earlier that didn't work:

$("td").on("dblclick","td",function(){ 
   //THIS DIDN'T FOR ELEMNTS ADDED AFTER PAGE LOAD

});

Even tried adding a class to newly added <td> and passed it in the second parameter,but it didn't seem to work.

Anyone please explain,whats the problem in the second case.?

Varun
  • 1,950
  • 2
  • 8
  • 16

1 Answers1

2

Anyone please explain,whats the problem in the second case.?

You are saying "Even tried adding a class to newly added <td>" which implies that you are creating new <td> elements.

The event handler has to be bound to an existing, "static" ancestor of the elements that are dynamic.

Your handler, $("td").on("dblclick","td",function() {}) doesn't make much sense. It would listen to clicks on table cells inside other table cells.

Have a look at the jQuery tutorial Understanding Event Delegation to learn more about event delegation.

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072