I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the HTML code below to a container element with some values.

Where can I put this HTML to re-use in a smart way?

<a href="#" class="list-group-item">
    <div class="image">
         <img src="" />
    </div>
    <p class="list-group-item-text"></p>
</a>

JQuery

$('.search').keyup(function() {
    $('.list-items').html(null);

    $.each(items, function(index) {
        // APPENDING CODE HERE
    });
});

推荐答案

You could decide to make use of a templating engine in your project, such as:

If you don't want to include another library, John Resig offers a jQuery solution, similar to the one below.


Browsers and screen readers ignore unrecognized script types:

<script id="hidden-template" type="text/x-custom-template">
    <tr>
        <td>Foo</td>
        <td>Bar</td>
    <tr>
</script>

Using jQuery, adding rows based on the template would resemble:

var template = $('#hidden-template').html();

$('button.addRow').click(function() {
    $('#targetTable').append(template);
});

Jquery相关问答推荐

从 React 到 Node 服务器的 ajax 调用中的数据未定义

如何在没有实体框架的情况下在 ASP.NET 上使用 ajax 和 jquery 从列表创建数据表

jquery如何判断ajax调用的响应类型

为什么要两次声明 jQuery?

从 JQuery.ajax 成功数据中解析 JSON

如何在 jQuery 中为 getJSON 设置缓存 false?

如何在 HTML选项标签上显示工具提示?

jQuery-UI 的自动完成不能很好地显示,z-index 问题

使用 jQuery 验证插件自定义日期格式

专业的基于 jQuery 的 Combobox 控件?

使用 jQuery 将宽度设置为百分比

jQuery - 多个 :not Select 器

jQuery '如果 .change() 或 .keyup()'

jQuery ajax (jsonp) 忽略超时并且不触发错误事件

消除移动 Safari 中点击事件的 300 毫秒延迟

判断文本框是否有空值

jQuery 发送字符串作为 POST 参数

如何获得两个日期对象之间的小时差?

jQuery clone() 不克隆事件绑定,即使使用 on()

如何使用 JQuery 删除onclick?