用正则表达式模仿Mustache插件的功能
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <script type="text/javascript"> var dd=[{"wang":"王1","li":"李1"},{"wang":"王2","li":"李2"},{"wang":"王3","li":"李3"}]; var dll=[{"qian":"钱1","sun":"孙1"},{"qian":"钱2","sun":"孙2"}]; var data={"dd":dd,"dll":dll} var aa="{{#dd}}<div>{{id}}</div><span>{{wang}}</span><div>{{li}}</div>{{/dd}}{{#dll}}<div>{{id}}</div><span>{{qian}}</span><div>{{sun}}</div>{{/dll}}"; var bb=aa.replace(/{{#(\w+)}}(.+){{\/\1}}/g,function(){ return gg(data[arguments[1]],arguments[2]); }) console.log(bb) function gg(dd,aa){ var chuan=""; for(var i=0;i<dd.length;i++){ var ee=dd[i]; var bb=aa.replace(/{{(\w+)}}/g,function(a,b){ if(b=='id'){ return i+1; } return ee[b]; }); chuan+=bb; } return chuan; } </script> </body> </html>
请爱好前端技术的朋友,联系我,有问题大家一起讨论