2011-02-03 56 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