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

How to access elements rendered into the page with Mustache using jQuery

我正在使用小胡子模板和 ajax 将一些内容呈现到我的页面中。然后我想使用另一个函数 (componentLoaded) 与一些元素交互(根据页面位置隐藏它们)。

显然这个函数需要 运行 在项目呈现在页面上之后,但这是如何完成的?我正在尝试在我的 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() 是另一个文件中的函数。

为什么不在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);
        }
    });
}

顺便说一句,当你真的想使用承诺时,你的问题的答案是这样写的:

...
}).then(componentLoaded);
...

由于您在将函数 componentLoaded() 传递给 promise 的同时执行了函数,因此 promise 没有什么可以执行的了!