1 回答

TA貢獻2041條經驗 獲得超4個贊
原因是jQuery load方法的實現(xiàn)是先填充DOM再調用回調函數(shù)。
下面是jQuery load方法的源碼:
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
你傳入的文件路徑text/text
最終仍然是通過ajax
去獲取的,獲取了文件內容后,在done
方法里使用.html()
把內容放到了DOM元素中,然后調用complete
函數(shù),而傳入參數(shù)中的回調函數(shù)callback
是在complete
函數(shù)中調用的。
所以,是先調用的self.html(data)
,渲染好了DOM,然后再調用回調函數(shù)。
添加回答
舉報