<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>
最佳答案
使用函数进行替换:
<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>
关于javascript - 如何将 Javascript 反向引用传递给键或函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377904/