Can jQuery template bind to a raw array

怎甘沉沦 提交于 2019-12-03 13:44:20
<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" );
<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}} works everywhere ( ${} wont work in strings in the template )

${} didn't work for me with an array of strings ['A String','Another String','Yet Another String'] , but {{= $data}} does. thanks!

You want to look into the {{each}} template tag.

In this case, I don't think that jQuery.tmpl is really the best way to do this. It would be much easier in my opinion just to use a standard for loop.

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!