多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## js自定义模板 [TOC] * * * * * >[info] #### 1.知识要点 * jquery * 利用replace函数替换标签 >[info] #### 2.核心代码 ~~~ tpl.replace("{{name}}", n.name) ~~~ >[info] #### 3.效果图 ![](https://box.kancloud.cn/2f59a7f3546835db409d4e541f9fb07b_653x170.png) >[info] #### 4.实例代码 ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>自定义模块</title> <style> body{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;margin:0;padding:0;} .list{ border:solid 1px #ccc; margin:50px auto; width:500px; text-align: center; } li{ list-style-type: none; margin-bottom:5px; } li:first-child{ font-weight:bold; } .list li div{ display: inline-block; width:80px; } </style> </head> <body> <ul class="list"> <li> <div>姓名</div> <div>年龄</div> <div>性别</div> </li> </ul> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script> var tpl = "<li><div>{{name}}</div><div>{{age}}</div><div>{{sex}}</div></li>"; var list = $(".list"); var data = { 1: {name: "王守仁", age: 58, sex: "男"}, 2: {name: "徐阶", age: 81, sex: "男"}, 3: {name: "张居正", age: 58, sex: "男"}, 4: {name: "娄谅"} }; $.each(data, function (i, n) { list.append(tpl.replace("{{name}}", n.name).replace("{{age}}", n.age||"未知").replace("{{sex}}", n.sex||"未知")); }); </script> </body> </html> ~~~