2010-12-07 69 views
3
<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> 

回答

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> 
+0

我不知道这一点!每天都是上学的日子..谢谢! – Connell 2012-06-01 11:39:42

0
var my_image = img_template.replace(/{(.+?)}/g, function(match, group1){ 
    return img_info[group1]; 
}); 
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); 
相关问题