因為 jQuery Templat 似乎目前回傳的似乎是物件,而不是 html 的字串,所以若要做字串相加會無法處理
只好找網路上的範例,然後封裝成 jQuery Plugin 的格式來用
函式部份 $().tmpl_html
/**
* 把 jQuery Template 的 html 傳回來
* 因為 jQuery Template 似乎沒有提供此功能,只好自己包一個 jQuery Plugin 的介面
* @author Leo Kuo <et282523@hotmail.com>
*/
(function($)
{
$.fn.tmpl_html = function(data)
{
return this.template("#" + this.attr('id'))($, {data: data}).join('');
};
})(jQuery);
Demo 效果
<!-- 容器 -->
<div id='base'></div>
<!-- 載入 jquery template -->
<script type="text/javascript" src='/global/js/jquery.js'></script>
<script type="text/javascript" src='/global/js/jquery.tmpl.js'></script>
<!-- jQuery Templte 的擴充 -->
<script type="text/javascript">
/**
* 把 jQuery Template 的 html 傳回來
* 因為 jQuery Template 似乎沒有提供此功能,只好自己包一個 jQuery Plugin 的介面
* @author Leo Kuo <et282523@hotmail.com>
*/
(function($)
{
$.fn.tmpl_html = function(data)
{
return this.template("#" + this.attr('id'))($, {data: data}).join('');
};
})(jQuery);
</script>
<!-- 樣版 -->
<script type="text/x-jquery-tmpl" id="myTempl">
<div>${Name}</div><div>${Id}</div>
</script>
<!-- 效果 Demo -->
<script type="text/javascript">
$(function()
{
var param = {Name:'Leo', Id:'1234'};
var html = ($('#myTempl').tmpl_html(param));
$('#base').html(html);
console.log(html);
});
</script>
程式碼
https://github.com/fishingboy/Library/blob/master/jQuery-Plugin/jquery.tmpl.html.js
文章標籤
全站熱搜
