views:

32

answers:

3

I have a search page that loads results. Each row has a 'Delete' button next to it which I want to fire a particular Javascript function on my page using some parameters specific to that row.

Is it best to put the function call directly into the HTML being generated, e.g. onclick="deleteFunc(<params from results array>);" or should I instead attach the jQuery click events? I've been opting towards the latter, but in this case I'm not sure the best way to do that.

Can I somehow attach events to some HTML even if it is not yet added to the page? If not, I'll have to add all the results to the page, including the array index of each row from the search results, then attach the click event to the button while accessing that row's parameters from the original array using the index I stored in a hidden HTML field. This seems like a lot of work re-correlating everything, when there is a point at which I build the HTML where I have all the parameters that particular row's delete button needs.

Assuming I use jQuery's click events, is there some danger in running out of memory? I may have a thousand rows coming back. If so, what happens when it runs out of memory?

Another option would be to serialize each array row's JSON into a hidden field next to the delete button, which I could then retrieve later. Seems like that would be more memory efficient, but also seems ugly.

+5  A: 

Think the .live() JQuery method may work for you.

Attach a handler to the event for all elements which match the current selector, now or in the future.

Andy Robinson
That's brilliant. Never knew this existed!
elduderino
@Andy: would that not require me to ensure that every search result I bring back have a globally-unique ID? Otherwise when the search is run a second time, the original 'live' bind from array index 3 will be bound to the new resulting row #3.
RenderIn
Depends on how you are refreshing the results. If you use .remove() then the binding will also be removed, http://api.jquery.com/remove/, so by adding new items the .live() method will reattach to the new items you've just added.
Andy Robinson
+1  A: 

You can add events to dynamically added elements using the .live() method.

$('.element').live('click', function() {
  // do some stuff.
});
Malabar Front
A: 

Yes you can attach events to HTML elements even before they exist using live method

$('.selector').live('click',function(){

alert('Do something here!');

});
dejavu