如何使用Mustache模板向下拉列表添加选项?

时间:2012-01-25 16:04:51

标签: javascript jquery templates mustache

这是我的javascript对象,我想添加选项到下拉列表?我希望属性名称作为值和属性值在每个选项中作为文本?

{ "": "", "CSharp40": "C# 4.0", ".NET": ".NET", "JQuery": "JQuery", "Javascript": "Javascript" }

输出如下

<select id="courses"> 
    <option value=""></option>
    <option value="CSharp40">C# 4.0</option>
    <option value=".NET">.NET</option>
    <option value="JQuery">JQuery</option>
    <option value="Javascript">Javascript</option>
</select>

你能告诉我如何为此编写Mustache模板吗?提前致谢

2 个答案:

答案 0 :(得分:6)

同意由于您的数据是一个列表,因此它应该在一个数组中。但是,我建议你使用这种Mustache-ier技术,而不是手动迭代你的数组。测试

var courses = [
    {val: "", title:""},
    {val: "CSharp40", title: "C# 4.0"},
    {val: ".NET", title: ".NET"},
    {val: "JQuery", title: "JQuery"},
    {val: "Javascript", title: "Javascript"}
];

var template = "<select id='courses'>{{#list}}<option value='{{val}}'>{{title}}</option>{{/list}}</select>";

// because Mustache doesn't like anonymous arrays of objects
var rendered_template = Mustache.to_html(template, {"list":courses} );

$('#list-container').html(rendered_template);

答案 1 :(得分:3)

理想情况下,您的对象将是一个对象数组:

var obj = [{val:"",title:""},{val:"CSharp40",title: "C# 4.0"},{val: ".NET",title: ".NET"},{val: "JQuery",title: "JQuery"},{val: "Javascript",title: "Javascript"}];

//open select
var output = '<select id="courses">';
//add each value
$.each(obj,function(){
    output += Mustache.render('<option value="{{val}}">{{title}}</option>', this);
});
//close select
output += '</select>';

//output
$(function(){ //on document ready
    $('body').html(output); 
});