views:

36

answers:

4

Hello,

I've a webpage fullfilled by a JS script that creates a lot of HTML tables.

Number of <table> created can vary between 1 and 1000 with 100 cells in each of it.

My question is : how to bind efficiently the click on theses tables? Should I bind the click on each cell of the <table> or directly to the <table> itself and retrieve the cell clicked in the bind function?

Or have you another idea?

Thanks

P.S: I'm using IE6+

A: 

bind event on table for faster execution and get cell details inside that function.

Praveen Prasad
+3  A: 

As it seems that you use jQuery, you should use the delegate() method on the table, e.g.:

$('table').delegate('td', 'click', function() {
    // $(this) refers the the clicked cell
});

This will bind one event handler to the table and capture the bubbled up click events.

Binding so many event handlers, i.e. an event handler to every cell, is indeed not a good idea, especially not in IE (for performance reasons).

Felix Kling
+5  A: 

I suggest you use delegate.

$("table").delegate("td", "click", function(){
    alert($(this).text()); // alert td's text.
});

delegate will just bind one event, and that is to the context(in this example, the <table>).

Reigel
Thanks for reply :)
Arnaud F.
A: 

you can find a similar toppic here: http://stackoverflow.com/questions/3822146/large-table-with-lots-of-events-is-using-event-bubbling-more-effecient/3822327#3822327

i would use this way:

$("table#yourTable").click(function(evt){
   if($(evt.target).is('td')) {
     //do whatever you want to do
   }
})
meo