jQuery模板可以绑定到原始数​​组

时间:2011-05-24 05:12:36

标签: jquery jquery-templates

鉴于

<div id="place_holder" />

<script id="template" type="text/x-jquery-tmpl">
WHAT DO I PUT HERE
</script>

var array_of_ints = [1,2,3]

$( "#template" )
        .tmpl( array_of_ints   )
        .appendTo( "#place_holder" );

我可以在模板中添加什么内容?

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

4 个答案:

答案 0 :(得分:8)

<div id="place_holder" />

<script id="template" type="text/x-jquery-tmpl">
    {{= $data}}
</script>

var array_of_ints = [1,2,3]

$( "#template" )
    .tmpl( array_of_ints   )
    .appendTo( "#place_holder" );

{{= $ data}}无处不在($ {}无法在模板中的字符串中使用)

答案 1 :(得分:4)

<ul id="place_holder">
</ul>

<script id="template" type="text/x-jquery-tmpl">
    <li>${}</li>       
</script>

var array_of_ints = [1,2,3]

$("#template")
    .tmpl(array_of_ints)
    .appendTo( "#place_holder" );

答案 2 :(得分:1)

$ {}对我来说不适用于一个字符串数组['A String','Another String','Yet Another String'],但是{{= $ data}}呢。谢谢!

答案 3 :(得分:-1)

您想查看{{each}}模板标记。

在这种情况下,我认为jQuery.tmpl确实是最好的方法。在我看来,使用标准for循环会更容易。

var array_of_ints = [1,2,3];

//creates the ul
var ul = $('<ul></ul>');

//creates the LI's
for(var i = 0; i < array_of_ints.length; i++){
    ul.append('<li>' + array_of_ints[i] + '</li>');
}

//adds to the placeholder
$('#placeholder').append(ul);

http://jsfiddle.net/LeKYu/