<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" );
在 jQuery 模板中显示 Value
或 Choice
的正确语法是什么?
最佳答案
需要进行一些更改: 1) 拆分下拉模板以选择标签模板和选项模板。 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>
关于javascript - 使用 jQuery 模板访问多维 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4890411/