我有一张 table :
<table id="my-table" border="1">
<tr>
<td>Apples</td>
</tr>
</table>
我在其中附加一行:
$('#my-table').append('<tr><td>Oranges</td></tr>');
这是一个非常基本的示例和一个简单的附加。在我当前的项目中,表格要大得多,并且更改也更加复杂。
还有其他方法可以解决这个问题吗?我的意思是,如果我对表进行更改,我需要返回到 JS 文件并对附加进行更改。似乎有点多余。这可能是一个荒谬的问题,但我很好奇是否有一种简化的方法。
最佳答案
使用客户端模板。我更喜欢 Handlebars 。所以你有一个像
这样的模板<script id="table-row-template" type="text/x-handlebars-template"> <tr><td>{{name}}</td><td>{{second_name}}</td><td>{{age}}</td></tr> </script>
包含在您页面中的某个位置。
使用 AJAX 从服务器获取数据并使用模板:
$.ajax({ url: 'mysite.com/tableRowData', dataType: 'json', success: function(response) { var source = $("#table-row-template").html(); var template = Handlebars.compile(source); $('#myTable tbody').append(template(response)); // Notice tbody. } });
通过这种方式,您可以将每个表的模板保存在不同的文件中,同时保留 HandleBars 模板。当您在append方法中编写HTML时,这种方法可以让您摆脱这种丑陋的语法,因为有时它很难阅读,例如
$('#myTable tbody').append('<tr><td><span class="..">...</span></td><td><img src="..."><span class="...">...</span></td>....</tr>');
此外,由于您仅从服务器检索 JSON 数据,因此可以对应用程序进行多种设计
关于javascript - 使用 jQuery 附加表格行 - 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18873235/