2013-03-14 44 views
4

我的第一個問題在這裏:)。事實上,我需要在這樣的對象的陣列的形式加載數據:使用jQuery生成文章列表的正確方法

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?

謝謝!

+1

檢查模板。 Ex http://stackoverflow.com/questions/13487647/understanding-jquery-template – 2013-03-14 06:09:41

+0

謝謝。我會檢查出來的! – yaditya 2013-03-14 22:40:47

回答

2

感謝您的答案您的模板字符串。我結束了使用Mustache.js使我的代碼更好。感謝Murali提供的jQuery模板鏈接,這讓我對一些可用的HTML模板庫做了更多的研究。我之所以沒有去jQuery模板,是因爲它已經停止了,並且沒有得到jQuery團隊的支持。

+0

鬍子很棒。你也可以看看Handlebars(http://handlebarsjs.com/),這是鬍鬚兼容的。想知道差異嗎?堆棧溢出救援一如既往:http://stackoverflow.com/questions/10555820/what-are-the-differences-between-mustache-js-and-handlebars-js – Nobita 2013-06-27 00:44:36

+1

是的,我也用了很多Handlebars,很多更好的方式來使用HTML模板而不是保守的方式。感謝您指出了這一點。 – yaditya 2013-10-22 23:37:41