主要强调正则replace的妙用,之前都没有这样使用过replace
上一篇文章链接:http://blog.csdn.net/xiaomogg/article/details/53270321
//格式化字符串方法 function formateString(str,data) { return str.replace(/\{#(\w+)#}/g,function(match,key) { return typeof data[key] === undefined ? "" : data[key] }); }; //基础导航 var Nav = function(data) { //基础导航模板 this.item = '<a href="{#href#}" title="{#title#}">{#name#}</a>'; //传教字符串 this.html = ""; //格式化数据 for (var i = 0,len = data.length; i < len; i++) { this.html += formateString(this.item,data[i]); } return this.html; }; //带有消息提示信息的组件模板************ var NumNav = function(data) { //消息提示信息组件模板 var tpl = '<b>{#num#}</b>'; //装饰数据 for (var i = data.length - 1; i >= 0; i--) { data[i].name += data[i].name + formateString(tpl,data[i]); } //继承基础导航类,并返回字符串 return Nav.call(this,data); } //带有链接地址的导航 var LinkNav = function() { //链接地址模板 var tpl = '<span>{#link#}</span>'; //装饰数据 for (var i = data.length - 1; i >= 0; i--) { data[i].name += data[i].name + formateString(tpl,data[i]); } //继承急促累导航,并放回字符串 return Nav.call(this,data); }; //创建导航 var nav = document.getElementById("nav"); nav.innerHTML = NumNav([{ href: "http://www.baidu.com",title: "百度一下,百度会死人的",name: "百度",num: "100" },{ href: "http://www.taobao.com",title: "淘宝商城",name: "淘宝",num: 2 },{ href: "http://www.qq.com",title: "腾讯首页",name: "腾讯",num: "3" } ])
html调用:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>`</title> </head> <body> <div id="nav"></div> <script src="template2.js"></script> </body> </html>