How to trigger a function when new elements are dynamically loaded?

和自甴很熟 提交于 2020-01-06 16:21:35

问题


I have elements being loaded onto the page via Script A. which is old school javascript

Script B does things to these elements.

Script B works on the elements initially loaded, but when Script A loads new elements, Script B doesn't know about it.

Live, delegate and bind won't work as Script Bs function is a custom event.

And I'm wondering, surely there is a general fucntion in jQuery which just wakes up and says some ajax just happpend. Then all I'd need to do is repeat Script Bs function.


That's the abstract. I dont really want to give more code as I dont think it helps. To give you an idea of what i want to achieve, Script A is a javascript infinite scroll for Tumblr. Script B is fading images in as they enter the viewport. It works, but only with the first set of images conventionally loaded.

Been stuck on this for four hours and not even close to figuring it out.

Thanks


EDIT Using livequery plugin like so does not work, but it seems tantilising (!) :-/ Maybe it just needs a tweek?

$('.theImage').livequery(function() { //.theImage being the dynamically loaded divs
$(this).waypoint(function() { //waypoint being Script B which fades in .theImage
   $(this).animate({opacity: 1}, 'slow');
});
});

回答1:


Use the following code to re-call script B everytime an ajax request is completed:

$(document).ajaxSuccess(function(e, xhr, options) {
  // The code here will be called every time
  // an ajax request has completed successfully.
  // Your code may assume that the DOM has been updated.
});


来源:https://stackoverflow.com/questions/7910889/how-to-trigger-a-function-when-new-elements-are-dynamically-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!