首页 > 解决方案 > 如何使用 jQuery 创建和附加 HTML?

问题描述

我想知道如何使用 jQuery 创建和附加 HTML。显然,像这样编写 20-25 行甚至更多行代码是很乏味的:

 "<h1>"+response.name+"</h1>" +
   "<p>"+response.description+"</p>" + and so on

标签: jqueryhtml

解决方案


如果你有一个(或多或少)固定的标记结构并且反复想用变量值填充它,你可以考虑使用模板。

有大量的 JS 模板引擎,但为了简单起见,这里有一个使用mustache.js的示例:

<script src="mustache.js" type="text/javascript"></script>

<script id="template" type="x-tmpl-mustache">
    <h1>{{name}}</h1>
    <p>{{description}}</p>
    {{#optionalVar1}}
        <p>{{#optionalVar1}}</p>
    {{/optionalVar1}}
</script>

<script type="text/javascript">
    var template = document.querySelector('#template').innerHTML;

    /* "response" should be an object containing named members as
     * in the template above. "{{name}}" refers to "response.name" */
    var rendered = Mustache.render(template, response);
    document.querySelector('#output').innerHTML = rendered;
</script>

推荐阅读