我已經通過並嘗試了幾個同步調用函數的例子,但它似乎並沒有爲我工作。我使用外部句柄模板來生成一個加載了數據的'parent'html元素,然後在加載之後,我想從我創建的'child'模板(使用它們自己的數據)添加html。這兩個函數調用都調用相同的函數,但僅傳遞不同的模板/數據。以下是我對此的代碼 - 任何幫助表示讚賞。謝謝!不能讓這兩個函數同步調用
var loadSimpleCollection = function(templateFile, dataFile, containerSelector) {
var deferred = $.Deferred();
$.get(templateFile, function(text) {
// Extract HTML from the template file
var raw_template = text;
// Compile that into an handlebars template
var template = Handlebars.compile(raw_template);
// Retrieve the container where the data will be displayed
var container = $(containerSelector);
// Fetch collection data from JSON file
$.getJSON(dataFile, function(data, status, xhr) {
$.each(data,function(index,element){
var html = template(element);
container.append(html);
});
});
});
return deferred.promise();
}
loadSimpleCollection('template1.hbs', 'data1.json', '#parent-div').then(loadSimpleCollection('template1.hbs', 'data2.json', '#child-div'));
可能要包裝你'then'表達,否則它被立即調用。例如'.then(function(){loadSimpleCollection(...)})' –
你需要在'container.append(html);' –