开发者

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

开发者 https://www.devze.com 2023-01-08 08:38 出处:网络
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.

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 ru开发者_JAVA技巧nning 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!');

});
0

精彩评论

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