substitute Simple JavaScript Template :

参考地址:http://www.planabc.net/2011/05/31/simple_javascript_template_substitute/

源码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"
>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>

<script type="text/javascript">
function substitute (str, obj) {
alert(
"456");
if (!(Object.prototype.toString.call(str) === '[object String]')) {
return '';
}

// {}, new Object(), new Class()
// Object.prototype.toString.call(node=document.getElementById("xx")) : ie678 == '[object Object]', other =='[object HTMLElement]'
// 'isPrototypeOf' in node : ie678 === false , other === true
if(!(Object.prototype.toString.call(obj) === '[object Object]' && 'isPrototypeOf' in obj)) {
return str;
}

// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
return str.replace(/\{([^{}]+)\}/g, function(match, key) {
var value = obj[key];
return ( value !== undefined) ? ''+value :'';
});
}


var obj = {
url:
"http://www.plannabc.net/",
title:
"落草为根——专注前端技术&关注用户体验",
text:
"怿飞's Blog"
};
var link = '<a href="{url}" title="{title}">{text}</a>';

$(
function(){
alert(substitute(link, obj));
});


</script>

</head>
<body>

</body>
</html>

  

posted @ 2011-09-01 03:05  wangkangluo1  阅读(354)  评论(0编辑  收藏  举报