如何动态创建Jquery Template输入数据

时间:2012-03-20 16:22:05

标签: javascript jquery jquery-templates

在Jquery Template网站上,他们给出了这个例子。(http://api.jquery.com/jQuery.template/

<script>
    var movies = [
        { Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" },
        { Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
        { Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
    ];

    var markup = "<tr><td colspan='2'>${Name}</td><td>Released: ${ReleaseYear}</td><td>Director: ${Director}</td></tr>"

    /* Compile markup string as a named template */
    $.template( "movieTemplate", markup );

    /* Render the named template */
    $( "#showBtn" ).click( function() {
        $( "#movieList" ).empty();
        $.tmpl( "movieTemplate", movies ).appendTo( "#movieList" );
    });
</script>

我唯一的问题是如何创建这个

var movies = [
    { Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" },
    { Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
    { Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
];

使用for循环动态数据?我尝试使用循环[非常脏的方式]创建这个结构,它没有工作(可能是因为我创建的是一个类似的字符串),我想它期望一个数组。

1 个答案:

答案 0 :(得分:2)

这是一个JSON对象数组。

myArray.push({name: depName, value: depValue});

使用push您可以添加新元素。从某处读取数据并将其插入阵列。