开发者

The best way to bind event on a cell element

I've a web page fulfilled by a JS script that creates a lot of HTML tables.

Number of <table> creat开发者_JAVA技巧ed 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?

P.S: I'm using IE6+


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>).


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).


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


you can find a similar toppic here: large table with lots of events, is using event bubbling more effecient?

i would use this way:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜