开发者

Javascript inside AJAX request

开发者 https://www.devze.com 2023-03-21 13:54 出处:网络
I have a little problem with an AJAX function: PAGE A stands for the page. PAGE X stands for the loaded content.

I have a little problem with an AJAX function:

  1. PAGE A stands for the page.
  2. PAGE X stands for the loaded content.
  3. RES A stands for the page results.
  4. RES B stands for some AJAX loaded content => new results.

PAGE A contains 20 results, each result can be removed and a new result is loaded via AJAX (PAGE X).

Example:

User is on PAGE A: --> PAGE A loads js "click" functions. --> Results are RES A (20x).

When the user removes a result from RES A (1x), AJAX loads a new result RES B (1x):

User is -still-开发者_开发技巧 on PAGE A. --> PAGE X is loaded with js "click" functions. --> Result is RES B (1x)

In order to add click functions to RES B, I have to reload a lighter JS but it multiplies the functions of RES A.

So when the user removes results from RES A (1x5 for 5 results removed), RES B result is multiplied 5x (the user gets 5x the same result instead of 1x).

Do you get it? In brief, the AJAX request is multiplied by x RES B instead of sticking to 1 request. Do you have any clue how I can keep my RES B 1x?

Thanks!


I think you re-binding click event every time while "reload a lighter JS". Javascript doesn't replace the event function - they are just concatenated. If you use jQuery use live to add click event. If you don't - clear current click events before reloading


Seems that events are being attached multiple times.
Use unbind().click() or unbind().bind('click'), or die().live() whatever are you using


Your explanation is really difficult to understand, but if I understood correctly your problem lies in the fact that you bind the same element multiple times.

The best solution in your case would be the use of jQuery .delegate('#datatable a', 'click', function(e){ /* DO STUFF */}) which allows to bind all the selector matching elements once (in this case for example if you had a table with id=datatable, every link that is inside of it will always be bound to that handler, even if you add more html to the table, or remove some) and you wouldn't have to worry about it later on.

However, if you don't use jQuery the only solution is to either unbind the events before you add them (to remove the already existing binds) and then bind them again.


What you need to do is process the result (1x) when you load it. A simple way can be to have a class added to the results when u load and removing it once u r done.

e.g.

$('.newresult .clickbutton').ready(function(){
   // Do something
});

$('.newresult').removeClass('newresult');
0

精彩评论

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

关注公众号