Я совершенно уверен, что я прошу просто и понятно, но и я устал и не вижу этого :(
Мой упрощенный пример:
function doSomething(){
doFirst();
doSecond();
}
function doFirst(){
$.when(
//doing an ajax call and getting a result
)
.then(
function(result){
// doing something with the result
$(document).append('<div id="first">I am first</div>');
}
);
}
function doSecond(){
$('#first').css({'color':'#900'});
}
doSomething();
Но мой текст не краснеет, как ожидалось. Я считаю, что это потому, что функция уже выполняется, но отложенная еще не записана в DOM.
Вы можете doFirst()
обещание, вернув обещание от doFirst()
:
function doFirst(){
/* return the '$.when' promise*/
return $.when(
//doing an ajax call and getting a result
)
.then(function(result){
// doing something with the result
$(document).append('<div class="first">I am first</div>');
}
);
}
function doSomething(){
doFirst().then(function(){
doSecond();
});
}
Будет также получить тот же результат, просто вернув ajax без $.when
поскольку $.ajax
возвращает обещание
function doFirst() {
/* return the ajax promise*/
return $.post('/echo/html/', {
html: '<div id="first">I am first</div>'
}).then(function (result) {
$('body').html(result);
});
}
id= first
в вашей демоверсии .... jsfiddle.net/xypLg/1
function doSomething() {
//pass a callback to doFirst which will get executed once the ajax request is completed
doFirst(function () {
doSecond();
});
}
function doFirst(callback) {
$.when(
//doing an ajax call and getting a result
).then(function (result) {
// doing something with the result
$(document).append('<div class="first">I am first</div>');
callback();
});
}
function doSecond() {
$('#first').css({
'color': '#900'
});
}
doSomething();
#
префикс для выбора идентификатора.
префикс для выбора класса.