簡體   English   中英

在遍歷jquery對象時添加html

[英]Adding html while iterating over jquery object

除了我現在正在做的事情之外,還有沒有更好的方法可以將稍微復雜的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個朋友,這似乎非常慢且需要大量服務器。

一種不錯的方式是使用模板引擎,把手(如上一個答案中所述)就是其中之一。 如果您的情況如此簡單,那么您也可以創建自己的。 另一個關鍵的事情是不要在循環內使用append,而是將它們構造為一個temp數組,最后將其添加到DOM中。 如果您的列表很大,並且將dom添加到數組中可能會很昂貴。

添加帶有占位符的模板html作為friendId

<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
}

演示版

您也可以使用$.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);
}

一種可擴展的解決方案是使用模板引擎並使服務器返回JSON響應。 看看Handlebars.js http://handlebarsjs.com/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM