2012-10-20 55 views
0

我的jquesy ajax調用返回此結果。使用jQuery模板嵌套列表

var clientData = [ 
    { name: "test1", id: 1, parentid: 0, desc: "test desc1" }, 
    { name: "test2", id: 2, parentid: 0, desc: "test desc1" }, 
    { name: "test3", id: 3, parentid: 0, desc: "test desc1" }, 
    { name: "test1-1", id: 4, parentid: 1, desc: "test desc4" }, 
    { name: "test1-2", id: 5, parentid: 1, desc: "test desc5" }, 
    { name: "test2-1", id: 6, parentid: 2, desc: "test desc6" } 
]; 

我想使用jQuery模板爲這個數據創建嵌套ul li列表。

like。

  • 試驗1(試驗DESC1)
    • 試驗1-1(試驗desc4)
    • 試驗1-2(試驗desc5)
  • 試驗2(檢驗DESC2)
    • 試驗2-1(試驗desc6)
  • 試驗3(測試desc3)

任何人都可以請幫我寫jQuery模板。

代碼我使用模板創建li元素,並將其添加到像UL ....

<script id="menuTemplate_inner" type="text/x-jquery-tmpl"> 

     {{if parentid == 0}} 
      <li class="f_level" id="cat_${id}"> 
     {{else}} 
      <li class="inner_level" id="cat_${id}"> 
     {{/if}}  
     ${name} (${desc}) 
     </li>  
</script> 

我不知道,使其嵌套

+1

和你到目前爲止嘗試過什麼 – rahul

+0

我已經創建了一個jQuery模板,但不知道如何製作嵌套列表。 –

+1

告訴我們代碼 – rahul

回答

1

一的方式,分層模板通常送入分級數據,所以他們可以更自然地調用子模板。下面的例子將是您的數據更合適的表示,並導致更簡單的模板:

var clientData = [ 
    { name: "test1", id: 1, parentid: 0, desc: "test desc1", children: [ 
     { name: "test1-1", id: 4, parentid: 1, desc: "test desc4" }, 
     { name: "test1-2", id: 5, parentid: 1, desc: "test desc5" } 
    ] }, 
    { name: "test2", id: 2, parentid: 0, desc: "test desc1", children: [ 
     { name: "test2-1", id: 6, parentid: 2, desc: "test desc6" } 
    ] }, 
    { name: "test3", id: 3, parentid: 0, desc: "test desc1" } 
]; 

現在,假設你不改變,你正在使用的數據的表示,你的確可以構建元素的層次結構從平坦陣列與單個模板,主要是因爲:

  • 模板可以調用自身遞歸,

  • 模板調用可以使用參數(其被合併物體)。

如果我們考慮一個模板作爲「常規」功能(畢竟,這正是它被編譯成),這將是有意義採取parentId參數,只渲染誰指定的父匹配的項目。您已經使用0(沒有父級)用於頂級項目,這很適合我們,並允許我們用當前項目遞歸調用函數作爲新父項。

讓我們從第一次調用開始。我們需要傳遞頂級父ID 0(但我們不會將其稱爲parentId以避免與數據項中現有的parentid屬性混淆)。矛盾的是,我們也必須通過數據數組。這似乎是多餘的,因爲它已經是tmpl()的第一個參數,但這是因爲被調用的模板只能看到當前項目,而不是原始數組,除非我們明確地通過它。由此產生的代碼是這樣的:

$("#menuTemplate_inner").tmpl(clientData, { 
    clientData: clientData, // Pass original array. 
    forParent: 0    // Start at top-level. 
}).appendTo("ul"); 

現在,模板本身。它有三個任務來執行:

  • 渲染當前的項目,如果它指定父匹配,

  • 暴露適當的類(f_level的頂層,inner_level以其他方式),可與實現在${}模板標籤和ternary conditional operator

  • 調用自身遞歸與原始數據陣列和當前項目作爲新的父母,這是由{{tmpl}}模板標籤來實現的。

生成的模板是:

<script id="menuTemplate_inner" type="text/x-jquery-tmpl"> 
    {{if parentid == $item.forParent}} 
     <li class="${ parentid ? 'inner_level' : 'f_level' }" id="cat_${id}"> 
      ${name} (${desc}) 
     </li> 
     <ul> 
      {{tmpl($item.clientData, { 
       clientData: $item.clientData, 
       forParent: id 
      }) "#menuTemplate_inner"}} 
     </ul> 
    {{/if}} 
</script> 

可以在this fiddle測試。

+0

HelloFrédéricHamidi, 感謝您提供這樣清晰且真正有用的答案... –