开发者

Create a dynamic table using jQuery

Which is the best way to create dynamic tables from scratch in jQuery and then populate them with data.

EDIT :

Assume data comes from a scr开发者_StackOverflow中文版ipt service and I need to create a table dynamically and populate them with the incoming values


There are a few ways to accomplish the actual creation of the table without plugins. For example:

$('body').append('<table id="myTable"></table>');

You can then use .append to append table headers and rows by calling the table's id. Using .html will allow you to populate the table.


DataTables is a feature-rich jQuery Table plugin. Without knowing the functionality required by your application, it's hard to make perfect recommendations, though.


There is nice short introcution to what you are looking for in here: Creating Dynamic Tables with jQuery


Writing in a closure to avoid global variables. You can move the code out of the closure (first and last lines) when you put it into your app.

Assigning the table to a variable helps since you've got a resource to manipulate later, instead of requerying which can be taxing. myTable is a jQuery object, hence the example html() call, that'll add <thead> and <tbody> tags to your table element.

Also note that when you manipulate any element's inner contents, it's always best to wrap all your content inside as few elements as possible, since it will increase manipulation speed.

(function() {
   var myTable = $('<table></table>');
   $('body').append(myTable);
   myTable.html('<thead></thead><tbody></tbody>');
})();


You can use jTemplates or DOM creation plugin to write easy to read code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜