我使用mustache模板和ajax將一些內容呈現到我的頁面中。然後我想使用另一個函數(componentLoaded)與某些元素進行交互(根據頁面位置隱藏它們)。如何使用jQuery訪問使用Mustache呈現到頁面中的元素
顯然這個函數需要在頁面上渲染項目之後運行,但是這是如何完成的?我想用我的Ajax調用的承諾延期對象,但是這似乎並沒有工作:
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()是在另一個文件中的函數。