jquery - 使用 jQuery 生成文章列表的正确方法

标签 jquery html

我在 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/

相关文章:

jquery - Bootstrap 3 更新会在 Bootstrap 对话框打开或关闭时摇动 UI。我怎样才能摆脱这种行为?

html - 带有内容的图 block 填充不一致

javascript - 在 html5 上检查在线状态的最佳方式

javascript - 位置固定,作用类似于相对位置(随页面滚动)

php - 在网页上记录,保存和播放保存的声音文件

javascript - chop 文本而不点击嵌套链接

javascript - Angular js中的日期表列排序问题

javascript - 外部 JS 在我的 html 文件中不起作用?

javascript - 如何使 Foundation 5 顶部栏(导航栏)元素使用所有可用空间

html - 将黑白视频转换为白色和一种颜色