How can I copy from a template node and fill with json data and append them to the document with javascript?
In some case, I need to copy from a node templa开发者_如何转开发te and fill some fields of the node with json data. How can I do that? For example in HTML file I have written such a template:
<div id="template" style="display:none">
<h1>{{name}}</h1>
<p>{{content}}</p>
</div>
and my json data is
[{"name":"A","content":"B"},{"name":"C","content":"D"},{"name":"E","content":"F"}]
and I want to generate three nodes and append them to the document.
Also, the
node maybe binded with some click event and I want the new node actions too.
You'd be best off using a templating library - my favourite is jQuery.tmpl but there are others.
You'd have to modify your template like so:
<script id='template' type='text/x-jquery-tmpl'>
<h1>${name}</h1>
<p>${content}</p>
</script>
then render it like this:
$('#template').tmpl(data).appendTo('body');
where data is your array. This will create a separate template instance for each member of the array.
For a quick guide to jQuery.tmpl have a look at my slides or my presentation.
If you want to bind events, either bind them after you've added the rendered template to the DOM, or use live or delegate.
加载中,请稍侯......
精彩评论