2011-02-03 57 views
2
<script id="dropdownTemplate" type="text/x-jquery-tmpl"> 
    <label for="${Name.toLowerCase()}">${Name}</label> 
     <select name="${Name.toLowerCase()}" id="${Name.toLowerCase()}_dropdown"> 
      <option selected='' value=''>-- Select a ${Name} --</option> 
      <option value="${$item.Options.Value}">${$item.Options.Choice}</option> 
     </select> 
</script> 

    var provinces = { 
     Name: "Province", 
     Options: [ 
      { Value: "AB", Choice: "Alberta" }, 
      { Value: "BC", Choice: "British Columbia" }, 
      { Value: "MB", Choice: "Manitoba" }, 
      { Value: "NB", Choice: "New Brunswick" }, 
      { Value: "NF", Choice: "Newfoundland" }, 
      { Value: "NS", Choice: "Nova Scotia" }, 
      { Value: "NT", Choice: "Northwest Territories" }, 
      { Value: "NU", Choice: "Nunavut" }, 
      { Value: "ON", Choice: "Ontario" }, 
      { Value: "PE", Choice: "Prince Edward Island" }, 
      { Value: "QC", Choice: "Quebec" }, 
      { Value: "SK", Choice: "Saskatchewan" }, 
      { Value: "YT", Choice: "Yukon" } 
     ] 
    }; 


    // Render the template with the provinces data and insert 
    // the rendered HTML under the "movieList" element 
    $("#dropdownTemplate").tmpl(provinces).appendTo("#movieList"); 

什麼是正確的語法,以顯示訪問多維JSON在我的jQuery模板來ValueChoice使用jQuery模板

回答

4

需要幾個更改: 1)將下拉tempalte拆分爲選擇標籤模板和選項模板。 2)使用嵌套模板選項填充下拉選項。 3)將各省作爲數組對象傳遞。

下面給出的是腳本變化:

<script id="dropdownTemplate" type="text/x-jquery-tmpl"> 
    <label for="${Name.toLowerCase()}">${Name}</label> 
     <select name="${Name.toLowerCase()}" id="${Name.toLowerCase()}_dropdown"> 
      <option selected='' value=''>-- Select a ${Name} --</option> 
      {{tmpl(Options) "#optionTemplate"}} 
     </select> 
</script> 

<script id="optionTemplate" type="text/x-jquery-tmpl"> 
    <option value="${Value}">${Choice}</option> 
</script> 
<div id="movieList"></div> 
<script> 
var provinces = { 
      Name: "Province", 
      Options: [ 
       { Value: "AB", Choice: "Alberta" }, 
       { Value: "BC", Choice: "British Columbia" }, 
       { Value: "MB", Choice: "Manitoba" }, 
       { Value: "NB", Choice: "New Brunswick" }, 
       { Value: "NF", Choice: "Newfoundland" }, 
       { Value: "NS", Choice: "Nova Scotia" }, 
       { Value: "NT", Choice: "Northwest Territories" }, 
       { Value: "NU", Choice: "Nunavut" }, 
       { Value: "ON", Choice: "Ontario" }, 
       { Value: "PE", Choice: "Prince Edward Island" }, 
       { Value: "QC", Choice: "Quebec" }, 
       { Value: "SK", Choice: "Saskatchewan" }, 
       { Value: "YT", Choice: "Yukon" } 
      ] 
     }; 


     // Render the template with the provinces data and insert 
     // the rendered HTML under the "movieList" element 
     $("#dropdownTemplate").tmpl([provinces]).appendTo("#movieList"); 
</script> 
+0

完美。我的模板管理也更好。謝謝! – 2011-02-03 19:22:55