I’m experimenting with .live() and .delegate() for elements that are added to DOM well after my JS is loaded.
This works:
$(".mouseRow tbody tr").live("click", function(event) { });
But this does not work and no errors are given, which makes me think it is a DOM timing thing:
$(".mouseRow").delegate("tbody tr", "click", function(event) { });
Am I calling the .delegate() function incorrectly, perhaps with the “tbody tr” statement? Or is this a problem with the DOM timing since the elements do not exist yet (which is why I used live() in the first place)?
IfYou’ve said in the comments that.mouseRowis a class you’re applying totrelements, you want:mouseRowis a class on thetableelement within which you want to hook clicks ontrelements. If thetable.mouseRowelements will exist as of when you’re hooking up your handlers, you probably want this:That hooks the
clickevent ontbodywithin thetable.mouseRow, and when it occurs checks the chain of elements from the one actually clicked up totbodyto see if any of them match the selectortr. If so, it calls the event handler withthisreferencing the row in question.Or as of jQuery 1.7, the recommendation is to use
onfor this sort of thing:(Note that the order of arguments is slightly different.)
Either way, you execute that statement when the
table.mouseRow tbodyis already in the DOM. If it won’t be there yet, you need to go further up the DOM, perhaps all the way todocument: