<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. JavaScript函數默認情況下是否通過引用或值返回對象?
- 6. 如何通過CHID函數返回父函數返回
- 7. 可以lisp函數返回引用或通過引用接收參數?
- 8. 通過引用或返回值jinja2
- 9. 如何通過javascript中的函數返回數組?
- 10. 如何通過引用返回對象?
- 11. Boost.Python - 如何通過引用返回?
- 12. 如何通過函數內部的回調函數返回值?
- 13. 如何通過Awesomium庫從javascript函數返回值?
- 14. 通過返回函數名
- 15. 通過鍵和返回值或空
- 16. C++:通過引用返回值返回
- 17. 如何通過「自動」返回類型函數的值返回
- 18. 助理返回值的函數參數(CALL通過引用)
- 19. 通過函數返回引用分配數組值
- 20. 從哈希鍵返回數組引用或返回子例程
- 21. 通過從JavaScript中的函數返回函數來修改div
- 22. 使用Javascript通過嵌套函數返回數組
- 23. 如何使用返回對象的函數通過引用進行綁定?
- 24. 如何通過其他函數返回函數
- 25. 如何通過ref禁用jquery數據函數的返回值?
- 26. PHPUnit測試函數的值通過引用和返回值
- 27. 函數返回值vs修改通過引用傳遞的值
- 28. 通過函數引用檢索返回類型?
- 29. 通過引用返回的函數傳遞對象
- 30. 通過類函數返回引用並返回C++中的整個對象?
我不知道這一點!每天都是上學的日子..謝謝! – Connell 2012-06-01 11:39:42