You must use event delegation . Event delegation takes advantage of the fact that bubbles ' events through the DOM , which means that many elements receive notification of the event of one of their descendant elements.
With jQuery, this is even simpler, as it smooths out some cross-browser inconsistencies in event handling and event bubbles.
Now let's say that you want to associate an event handler with each row in the table. A direct but inefficient way of handling this is to bind an event handler to each line. This is actually what you are doing now. Imagine that you are attaching one handler to a table and say, βHey, call this handler whenever something happens on one of my rows.β This is what the whole delegation of events is about. With jQuery 1.7, the event handling interface has been reorganized and made more consistent. Here is an example of how to link such a handler:
$('table.math').on( { keyup: function doMath (e) {
An additional benefit of event delegation is that it meets your criteria: "There is a problem when I want to .append new table elements. They do not respond to keyup." When delegating events, this automatically works for all descendants that match the selector, regardless of whether they are present when the handler is bound or dynamically added later.
To summarize, event delegation:
- more effective . You bind one handler instead of many
- works for dynamically inserted elements
source share