我正在使用 Mustache 模板和 ajax 将一些内容渲染到我的页面中。然后,我想使用另一个函数(componentLoaded)与某些元素进行交互(根据页面位置隐藏它们)。
显然这个函数需要在页面上渲染项目之后运行,但是这是如何完成的呢?我正在尝试在我的 ajax 调用上使用 promise 延迟对象,但这似乎不起作用:
var template = null;
//Get Template
function getTemplate() {
return $.get('mustache/components/block.mustache', function(response) {
template = response;
}).then(renderComponent());
}
//Render Template
function renderComponent() {
// Get Data
return $.ajax('JSON/testData.json',{
dataType: 'json',
success: function(data) {
if(template != null) {
for(var i = 0; i < data.blocks.length; i++) {
renderTemplate(template, data.blocks[i], $('#container'));
}
}
else {
console.error('Error: Template failed to load');
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.error('Ajax Error: ' + xhr.status + ' ' + thrownError);
}
}).then(componentLoaded());
}
/**
* Render the template onto the page
* @param template, The mustache template to render the data with
* @param data, {{object}} The data to render into the template
* @param target, {{object}} The jQuery object for the element to append the rendered data to
*/
function renderTemplate(template, data, target) {
var rendered = Mustache.render(template, data);
target.append(rendered);
}
/**
* Render the component
*/
$(document).ready(function() {
getTemplate();
});
请注意,componentLoaded() 是另一个文件中的函数。
最佳答案
为什么不在 success 函数中调用 componentLoaded() ?
function renderComponent() {
// Get Data
return $.ajax('JSON/testData.json',{
dataType: 'json',
success: function(data) {
if(template != null) {
for(var i = 0; i < data.blocks.length; i++) {
renderTemplate(template, data.blocks[i], $('#container'));
}
componentLoaded();
}
else {
console.error('Error: Template failed to load');
}
// or here
// componentLoaded();
},
error: function (xhr, ajaxOptions, thrownError) {
console.error('Ajax Error: ' + xhr.status + ' ' + thrownError);
}
});
}
关于javascript - 如何使用 jQuery 访问通过 Mustache 渲染到页面中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30870634/