jQuery .tmpl() 用法示例介绍

2020-05-17 06:26:28易采站长站整理

<input type="text" name="value[${num}]" value="${value}" placeholder="value" />
<button type="button" class="button small remove-param"><img src="http://huoche.7234.cn/images/jb51/igovxzqeu31.png" height="12" alt=""/></button>
<button type="button" class="button small add-param"><span><img src="http://huoche.7234.cn/images/jb51/3l5cxz4eqrs.png" height="12" alt=""/></button>
</li>
</script>

<script>
$(function(){
function addParam(key, value) {
var param_list = $('.param-list');
var num = param_list.find('li').length;

// build a template to clone the current row
var built = $('#new-param-tmpl').tmpl({
num: num,
key: key || '',
value: value || '',
});
if (key) param_list.prepend(built);
else param_list.append(built);

param_list.find('li:not(:last) .add-param').hide();
param_list.find('li:last .add-param').show();
param_list.find('li:not(:last) .remove-param').show();
param_list.find('li:last .remove-param').hide();
}

// bind events
$('.param-list .remove-param').live('click', function(){
$(this).parent().remove();
return false;
});
$('.param-list .add-param').live('click', function(){
addParam();
return false;
});

addParam();
})
</script>
</body>
</html>

实例2


<ul id="movieList"></ul>

<script id="movieTemplate" type="text/x-jquery-tmpl">
<li><b>${Name}</b> (${ReleaseYear})</li>
</script>

<script type="text/javascript">
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];

// Render the template with the movies data and insert
// the rendered HTML under the "movieList" element
$( "#movieTemplate" ).tmpl( movies )
.appendTo( "#movieList" );
</script>