[英]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.