一种简单快速的模板解析方法,活用with javascript版
//一种简单快速的模板解析方法,活用with var parseTpl = function( str, data ) { var tmpl = 'var __p=[];' + 'with(obj||{}){__p.push(\'' + str.replace( /\\/g, '\\\\' ) .replace( /'/g, '\\\'' ) .replace( /<%=([\s\S]+?)%>/g, function( match, code ) { return '\',' + code.replace( /\\'/, '\'' ) + ',\''; } ) .replace( /<%([\s\S]+?)%>/g, function( match, code ) { return '\');' + code.replace( /\\'/, '\'' ) .replace( /[\r\n\t]/g, ' ' ) + '__p.push(\''; } ) .replace( /\r/g, '\\r' ) .replace( /\n/g, '\\n' ) .replace( /\t/g, '\\t' ) + '\');}return __p.join("");', func = new Function( 'obj', tmpl ); return data ? func( data ) : func; }; //demo var ong={ name:"caoke", va:"va" } parseTpl("<%=va%><%for(var i=0;i<3;i++)%><%=i%>sfd<%=va%>",ong) //var __p=[];with(obj||{}){__p.push('',va,'');for(var i=0;i<3;i++)__p.push('',i,'sfd',va,'');}return __p.join("");