我已经通过并尝试了几个同步调用函数的例子,但它似乎并没有为我工作。我使用外部句柄模板来生成一个加载了数据的'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);' –