for (var i = 0, len = data.length; i < len; i++) {
fragment += template
.replace(/\{\{title\}\}/, data[i].title)
.replace(/\{\{href\}\}/, data[i].href)
.replace(/\{\{imgSrc\}\}/, data[i].imgSrc)
}
result.innerHTML = fragment;
方法二:
var doc = document,
template = doc.querySelector('#template').innerHTML,
result = doc.querySelector('.result'),
attachTemplateToData;
attachTemplateToData = function (template, data) {
var i = 0,
len = data.length,
fragment = '';
function replace(obj) {
var t, key, reg;
for (key in obj) {
reg = new RegExp('{{' + key + '}}', 'ig');
t = (t || template).replace(reg, obj[key]);
}
return t;
}
for (; i < len; i++) {
fragment += replace(data[i]);
}
return fragment;
};
result.innerHTML = attachTemplateToData(template, data);
JavaScript实现JS函数重载
var people = {
values: ["Dean Edwards", "Sam Stephenson", "Alex Russell", "Dean Tom"]
};
function addMethod(object, name, fn) {
var old = object[name];