[英]console.log processed before deferred object returned to .done
有關jQuery延遲對象的Pluralsight教程提供了這個示例,我在其中添加了一些console.log
。 它異步地將三個html文件加載到三個div中,並成功顯示在屏幕上“工作!”-但是console.log
正在打印“成功!”。 在實際完成處理之前將其連接到控制台。 如果將console.log
放在代碼的when
部分中,那也是一樣—它打印內容在實際加載到屏幕上之前已完成加載。
那么,為什么對DOM的處理按預期進行(成功時),但是console.log
消息的打印卻比成功更早?
var loadSection = function (options) {
if (typeof options !== 'object')
options = {
};
options.selector = options.selector || '';
options.url = options.url || '';
return $.get(options.url, function (result) {
$(options.selector).html(result);
console.log(options.url)
}, 'html')
}
$('#Load').on('click', function () {
$.when(loadSection({
url: 'Content1.html',
selector: '#Section1'
}), loadSection({
url: 'Content2.html',
selector: '#Section2'
}), loadSection({
url: 'Content3.html',
selector: '#Section3'
})
).promise()
.done(function (result) {
$('#Messages').append('Worked!<br/>')
console.log('success!');
});
});
在您的loadSection
函數中,更改
return $.get(options.url, function (result) {
$(options.selector).html(result);
console.log(options.url);
}, 'html')
至
return $.get(options.url, 'html')
.then(function (result) {
console.log(options.url);
return $(options.selector).html(result).promise();
});
這應該返回一個承諾,該承諾將在.html(result)
完成時解析,而不是在$.get
完成時解析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.