我在 SO 中的第一个问题 :)。我实际上需要以这样的对象数组的形式加载数据:
var data = [
{
'id': '1',
'firstName': 'Megan',
'lastName': 'Fox',
'picture': 'images/01.jpg',
'bio': 'bla bla bla bla.'
},
{
'id': '2',
'firstName': 'Robert',
'lastName': 'Pattinson',
'picture': 'images/02.jpg',
'bio': 'bli bli bli bli.'
}
然后我想使用这种结构在 HTML 中显示数据:
<div class="wrapper">
<article>
<header>
<h2>[firstName 1 here]<h2>
</header>
<section>
<p>[bio 1 here]</p>
</section>
</article>
<article>
<header>
<h2>[firstName 2 here]<h2>
</header>
<section>
<p>[bio 2 here]</p>
</section>
</article>
</div>
我创建的 JS 函数如下:
var loadArtists = function() {
var $tmpHtml = '';
for (var artist in artists) {
var objArtist = artists[artist],
fullname = objArtist.firstName + ' ' + objArtist.lastName,
bio = objArtist.bio,
id = objArtist.id,
pic = objArtist.picture;
$tmpHtml += '<article><header data-id="' + id + '"><h2>' + fullname + '</h2></header><section data-id="' + id + '"><div class="imgContainer"><img alt="' + fullname + '" src="' + pic + '" /></div><h2 class="hiddenName">' + fullname + '</h2><p>' + bio + '</p></section></article>';
}
$('div.wrapper').append($tmpHtml);
};
这些代码好吗?还是有更好、更优雅的方式来构建 HTML?
谢谢!
最佳答案
感谢您的回答。我最终使用了 Mustache.js 让我的代码更好。感谢 Murali 提供的 jQuery 模板链接,它让我对一些可用的 HTML 模板库进行了更多研究。我没有选择 jQuery 模板的原因是它已经停产,而且它不再得到 jQuery 团队的支持。
关于jquery - 使用 jQuery 生成文章列表的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15402322/