<script type='text/javascript'>
// I have template and info
var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
var img_info = {
src : 'http://myimage.com/img.jpg',
width: '100px',
height: '100px',
title: 'My Image'
}
// I want to put info to template but It's not work.
// How should I do ?
var my_image = img_template.replace(/{(.+?)}/g, img_info['$1']);
</script>
问问题
547 次
4 回答
4
使用函数进行替换:
<script type='text/javascript'>
var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
var img_info = {
src : 'http://myimage.com/img.jpg',
width: '100px',
height: '100px',
title: 'My Image'
}
var my_image = img_template.replace(/{(.+?)}/g, function(a,b){
return img_info[b];
});
</script>
于 2010-12-07T14:51:54.697 回答
1
var my_image = img_template.replace(/{(.+?)}/g, function(m,v){return img_info[v];});
例如http://www.jsfiddle.net/gaby/3Lu4h/
更多关于使用函数作为替换方法的参数
于 2010-12-07T14:52:40.513 回答
0
var my_image = img_template.replace(/{(.+?)}/g, function(match, group1){
return img_info[group1];
});
于 2010-12-07T14:52:53.547 回答
0
你需要一个回调函数replace()
。
var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
var img_info = {
src : 'http://myimage.com/img.jpg',
width: '100px',
height: '100px',
title: 'My Image'
};
// callback function will be executed for each match
var my_image = img_template.replace(/{([^}]+)}/g, function(match, group1) {
// return lookup value or the empty string
return img_info[group1] || "";
});
或者,以可重复使用的形式:
function HtmlTemplate(html) {
this.template = html;
this.render = function(info) {
return this.template.replace(/{([^}]+)}/g, function(match, group1) {
return info[group1] || "";
});
};
}
var imgTemplate = new HtmlTemplate("<img src='{src}' width='{width}' height='{height}' title='{title}' />");
// later
var img = imgTemplate.render(img_info);
于 2010-12-07T14:53:42.523 回答