除了我现在所做的方式之外,是否有更好的方法可以将有些复杂的 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 好友列表,样式很漂亮。当用户搜索 friend 时,整个内容 block 将被清空并附加结果(我正在使用自动完成)。然而,设计可能会改变并变得更加复杂,所以我正在寻找一种可扩展的方法来完成我上面的工作。
除了在 JavaScript 中创建 html 之外,还有更聪明的方法吗?也许使用 $.load() 并将每个 friend 作为参数传递?但如果您必须列出 100 个 friend ,这似乎非常慢并且需要大量服务器。
最佳答案
一个好的方法是使用模板引擎, Handlebars (如上一个答案中提到的)就是其中之一。如果您的场景像这样简单,您也可以创建自己的场景。另一个关键点是不要在循环内使用append,而是将它们构造成一个临时数组并最后将其添加到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
}
<强> 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);
}
关于javascript - 在迭代 jquery 对象时添加 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20777154/