准备工作
需要用到template.js以及jquery.js
template.js的cdn地址
:https://www.bootcdn.cn/template_js/jquery.js的cdn地址
:https://www.bootcdn.cn/jquery/
html编写
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <table> <thead> <tr> <td style="width: 10%;">序号</td> <td style="width: 40%">测试颜色</td> </tr> </thead> <tbody id="test_body"> </tbody> </table> <script src="./jquery.min.js"></script> <script src="./template.js"></script> </body> </html>
template模板编写
<script type="text/html" id="test_html"> {{if testList.length == 0}} <tr class="text-center"> <td colspan="5">暂无数据</td> </tr> {{else}} {{each testList as value i}} <tr> <td>{{i+1}}</td> <td> {{if value.color === 'red'}} <span style="color: red;">红色</span> {{/if}} {{if value.color === 'green'}} <span style="color: green;">绿色</span> {{/if}} {{if value.color === 'blue'}} <span style="color: blue;">蓝色</span> {{/if}} </td> </tr> {{/each}} {{/if}} </script>
js编写
var datalist = { testList: [{ color: 'red' },{ color: 'green' },{ color: 'blue' } ] } var html = template("test_html", datalist); $("#test_body").html(html);
实现效果
完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <table> <thead> <tr> <td style="width: 10%;">序号</td> <td style="width: 40%">测试颜色</td> </tr> </thead> <tbody id="test_body"> </tbody> </table> <script type="text/html" id="test_html"> {{if testList.length == 0}} <tr class="text-center"> <td colspan="5">暂无数据</td> </tr> {{else}} {{each testList as value i}} <tr> <td>{{i+1}}</td> <td> {{if value.color === 'red'}} <span style="color: red;">红色</span> {{/if}} {{if value.color === 'green'}} <span style="color: green;">绿色</span> {{/if}} {{if value.color === 'blue'}} <span style="color: blue;">蓝色</span> {{/if}} </td> </tr> {{/each}} {{/if}} </script> <script src="./jquery.min.js"></script> <script src="./template.js"></script> <script> var datalist = { testList: [{ color: 'red' },{ color: 'green' },{ color: 'blue' } ] } var html = template("test_html", datalist); $("#test_body").html(html); </script> </body> </html>