迭代jquery对象时添加html

时间:2013-12-25 22:10:49

标签: javascript jquery html

除了我现在正在做的方式之外,是否有更好的方法将某些复杂的html插入到页面中? :

function display(friends) {
    $(".row").empty();

    $.each(friends, function(index, friend) {
        var html = '<div class="profileImage" style="float:left;padding:20px; width:200px">';
        html += '<a href="/app/click/' + friend.id + '">';
        html += '<img  id="' + friend.id + ' " src="https://graph.facebook.com/' + friend.id + '/picture?width=200&height=200 " />';
        html += '</a>';
        html += '</div>';
        $(".row").append(html);
    });

目前我有一个很好的风格的Facebook好友列表。当用户搜索朋友时,整个内容块被清空并附加结果(我正在使用自动完成)。然而,设计可能会改变并变得更加复杂,所以我正在寻找一种可扩展的方式来完成上面的工作。

不是在javascript中创建html,而是有更聪明的方法吗?也许使用$ .load()并将每个朋友作为参数传递?但如果你要列出100个朋友,这似乎非常缓慢且服务器密集。

2 个答案:

答案 0 :(得分:2)

一个好的方法是使用模板引擎,把手(如前面的答案中所提到的)就是其中之一。如果您的场景很简单,您也可以创建自己的场景。另一个关键的事情是不要在循环中使用append,而是将它们构造为临时数组并最终将它添加到DOM中。如果你的列表很大并且附加到阵列中的dom可能会很昂贵。

使用placeId

的占位符添加模板html
<script type="text/html" id="template">
    <div class = "profileImage" style = "float:left;padding:20px; width:200px"> 
        <a href = "/app/click/{{friendId}}"> 
            <img id = "{{friendId}}" src = "https://graph.facebook.com/{{friendId}}/picture?width=200&height=200 " /> 
        </a>
        </div>
</script>

var $template = $('#template'),
    $row = $('.row');

function display(friends) {
    var rows = [];
    $.each(friends, function (index, friend) {
        var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
        rows.push(templateHtml);
    });

    $row.html(rows); //Append them in the end
}

<强> Demo

您也可以使用$.map

var $template = $('#template'),
    $row = $('.row');

function display(friends) {
     var rows = $.map(friends, function (friend) {
        var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
        return templateHtml;
    });
    $row.html(rows);
}

答案 1 :(得分:1)

可扩展的解决方案是使用模板引擎并使服务器返回JSON响应。 看看Handlebars.js http://handlebarsjs.com/

相关问题