您可以决定在项目中使用模板引擎,例如:
- github
- underscore.js
- handlebarsjs
如果您不想包括另一个库,John Resig提供了一个jQuery解决方案,与下面的类似。
浏览器和屏幕阅读器会忽略无法识别的脚本类型:
<script id="hidden-template" type="text/x-custom-template"> <tr> <td>Foo</td> <td>Bar</td> <tr></script>
使用jQuery,基于模板添加行将类似于:
var template = $('#hidden-template').html();$('button.addRow').click(function() { $('#targetTable').append(template);});


