How do I use some dom as a template, so something like
<div>
<span> v1 </span>
开发者_StackOverflow社区<span> v2 </span>
<span> v3 </span>
</div>
and then programmatically replace v1-v3 with some values (that i get off an xhr repsonse)
You can do something like this:
$template = $('<div><span>v1</span><span>v2</span><span>v3</span></div>');
$new_dom_element = $template.clone();
// do your thing with replacing the content.
You can simply store it as a string
, then drop it in a jQuery object whenever you need a new copy.
Once it is part of a jQuery object, you can traverse it just like it was already in the DOM, and update its content.
Something like this: http://jsfiddle.net/bZz96/
var div_template = "<div><span> v1 </span><span> v2 </span><span> v3 </span></div>";
$(div_template).find('span')
.text( function(i) { return 'some new value ' + i; } )
.end().appendTo('body');
Mustache.js is really good for this.
Microsoft is building a JQuery plugin (it might be incorporated into JQuery) for templates.
Microsoft, jQuery, and Templating
I'm still waiting to see if anything happens with it, but it seems promising. I just looked at the github repository and it looks like there have been some recent changes (within the last several days), so it's still in progress.
精彩评论