2015-04-15 134 views
0

假设我有jQuery代码,将外部html文件加载到模板。用胡子填充外部.html文件?

$('#myButton').click(function(){ 
    $('#content').load('file.html'); 
}); 

现在,我想填充file.html文件中的一些字段。那可能吗?

+0

是的,这是可能的。 – Celeo

+0

请考虑在这里包含'file.html'的内容(或者至少包含它可能包含的一个很好的代表性示例)。 –

回答

1

这是一个(未经测试的)如何做到这一点的例子。

$('#myButton').click(function() { 

    // load text into a hidden div. 
    $('#hiddenContent').load('file.html', function() { 

    // grab template from hidden div 
    var templateString = $('#hiddenContent').html(); 

    // compile the template string into a template object 
    var compiledTemplate = hogan.compile(templateString); 

    // apply some data to the template 
    var parsedTemplate = compiledTemplate.render({...some data}); 

    // finally, show the parsed template 
    $('#content').html(parsedTemplate); 
    } 
}); 

编辑:附加注释

理想情况下,你就不会加载file.html到一个DOM元素,因为它并不需要显示。只需加载文本。

此外,编译模板的计算量很大。在生产环境中,应该预编译这些模板。 Hogan拥有一个名为Hulk的命令行实用程序,它可以实现这一点。

0

也许这样的事情?

$('#myButton').click(function() { 
    $('#content').load('file.html', function() { 
    // do something to populate fields created by the loading of file.html 
    } 
});