简体   繁体   中英

What's the best way to attach JavaScript events to a list of AJAX-loaded search results?

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, eg 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.

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.

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

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

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

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

alert('Do something here!');

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM