How to simulate an append callback function?

2019-05-14 09:05发布

问题:

I know that .append() does not have any callback function, but when I try to do this:

$.onShadowboxFinished = function (f) {

var postid = $(f.link).parent().attr("id");
var loadUrl = "wp-admin/admin-ajax.php?action=mfields_show_post&p=" + postid;
$('#infos_wrap').load(loadUrl).append();
alert("loaded! test selector :"+$('a.projectimgs').first().attr("href"));

}

I am loading content ( links and images ) into the div #infos_wrap. Once all links and images are loaded, I want to manipulate content ( example : Select the links to add them to the shadowbox cache )

For now, the 4th line is executed before the 3th.

Thanks for your help !

PS : If someone want really to help ( i'd appreciate it ^^ )
You can check the site : http://www.tom-portfolio.fr/wp-login.php
login: visitor
pass: visitor
The javascript file is portfolio.js
Use your firebug or GoogleDev tools to view it!
Thanks a lot !

回答1:

What you want to do is use the callback function for the .load() function because it is asynchronous (meaning the code after it keeps executing until it recieves a response and fires its callback function):

var postid  = $(f.link).parent()[0].id,
    loadUrl = "wp-admin/admin-ajax.php?action=mfields_show_post&p=" + postid;

$('#infos_wrap').load(loadUrl, function () {
    alert("loaded! test selector :"+$('a.projectimgs').first()[0].href);
});

Note that .load() will replace the contents of #infos_wrap with the response from the AJAX call (#infos_wrap in this case) so we don't have to use .append() (internally .html() is used which replaces the HTML of the selected element(s) rather than appending the response).

Also note that I changed a couple instances of .attr() where it wasn't needed.

Documentation for .load(): http://api.jquery.com/load