<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>无标题文档</title> </head> <body> <div id='title'></div> <div id='product'></div> </body> <script language="javascript" src="test.js" ></script> </html>
// JavaScript Document var viewCommand= (function(){ var tpl= { product :[ '<div>' , '<img src ="{#src#}"/> ', '<p>{#text#}</p> ', '</div>' ].join(''), title :[ '<div class="main">', '<h2>{#title#}</h2>', '<p>{#tips#}</p>' , '</div>' ].join('') } , html=''; function formateString (str,obj){ return str.replace(/\{#(\w+)#\}/g,function(match,key){ return obj[key]; }) } var Action = { create : function (data,view){ if(data.length){ for(var i=0,len=data.length;i<len;i++){ html+=formateString(tpl[view],data[i]); } } else { html+=formateString(tpl[view],data ); } }, display : function (container,data,view){ if(data){ this.create(data,view); } document.getElementById(container).innerHTML=html; html=''; } } return function excute(msg){ msg.param=Object.prototype.toString.call(msg.param)==="[object Array]" ? msg.param : [msg.param]; Action[msg.command].apply(Action,msg.param) } })(); var productData = [ { src : 'command/02.jpg', text :' 桃花' }, { src : 'command/03.jpg', text :' 阳光' }, { src : 'command/04.jpg', text :' 绿色' } ], titleData= { title : '夏日温馨', tips:'暖暖的夏日' }; viewCommand({ command :'display', param : ['title',titleData,'title'] }) viewCommand({ command :'create', param : [ { src : 'command/01.jpg', text :'01 绿色' },'product'] }) viewCommand({ command :'display', param : ['product',productData,'product'] })