<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>
3
A
回答
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>
1
var my_image = img_template.replace(/{(.+?)}/g, function(m,v){return img_info[v];});
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);
相关问题
- 1. 通过引用或返回函数返回大量数据?
- 2. Javascript返回的对象属性通过引用或值返回?
- 3. JavaScript的子函数通过返回父函数返回
- 4. JavaScript函数默认情况下是否通过引用或值返回对象?
- 5. 可以lisp函数返回引用或通过引用接收参数?
- 6. Boost.Python - 如何通过引用返回?
- 7. 如何通过Awesomium库从javascript函数返回值?
- 8. 通过键和返回值或空
- 9. 通过函数返回引用分配数组值
- 10. 从哈希键返回数组引用或返回子例程
- 11. 通过从JavaScript中的函数返回函数来修改div
- 12. 通过javascript函数引用控件
- 13. 如何通过其他函数返回函数
- 14. PHPUnit测试函数的值通过引用和返回值
- 15. 通过引用返回的函数传递对象
- 16. 函数返回值vs修改通过引用传递的值
- 17. 如何通过ref禁用jquery数据函数的返回值?
- 18. javascript函数返回函数
- 19. 如何通过引用返回一个结构数组?
- 20. 通过函数返回数字
- 21. C++通过Const引用并通过Const返回引用
- 22. 返回函数Javascript
- 23. Javascript函数返回
- 24. 如何通过引用传递成员回调函数
- 25. 如何在JavaScript中通过引用传递变量?从ActiveX函数读取返回多个值的数据
- 26. 返回表的Oracle过程或函数
- 27. 通过ajax/javascript返回CollapsiblePanelExtender
- 28. 如何让Javascript“isPrototypeOf”函数返回true?
- 29. 如何从javascript函数返回值
- 30. Javascript,如何从foreach函数返回值
我不知道这一点!每天都是上学的日子..谢谢! – Connell 2012-06-01 11:39:42