javascript - 如何使用 jQuery 访问通过 Mustache 渲染到页面中的元素

标签 javascript jquery ajax mustache

我正在使用 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/

相关文章:

javascript - 将图像上传到运行时创建的指定文件夹和子文件夹

javascript - 如何在 JQuery 语句成功时制作简单的延迟

javascript - 为什么 Escape 键在 Ace 编辑器中不起作用?

javascript - 如何阻止 JS 函数完成直到回调执行完毕

jquery - 将数据属性与 jquery 验证一起使用

javascript - Google 的 Places API 和 JQuery 请求 - 来源 http ://localhost is not allowed by Access-Control-Allow-Origin

javascript - JQuery getJSON - ajax 解析错误

java - 在 JSP 中将 Javascript 值传递给 Java

javascript - 如何针对特定条件缩小数组?

javascript - 使用 jquery 访问脚本 block