/** * @author zhixin wen * @version 0.0.1 * @github https://github.com/wenzhixin/bootstrap-table * @blog http://wenzhixin.net.cn */ (function($) { 'use strict'; function Table($el, options) { this.$el = $el; this.options = options; } Table.prototype = { constructor: Table, init: function() { this.$el.addClass(this.options.class); this.$header = $(''); this.$el.append(this.$header); this.$body = $(''); this.$el.append(this.$body); this.initHeader(); this.initBody(); }, initHeader: function() { var that = this, html = ['']; this.header = { fields: [], styles: [], formatters: [] }; $.each(this.options.columns, function(i, column) { var style = column.align ? 'text-align: ' + column.align + '; ': ''; style += column.width ? 'width: ' + column.width + 'px; ': ''; that.header.fields.push(column.field); that.header.styles.push(style); that.header.formatters.push(column.formatter); html.push('' + column.title + ''); }); html.push(''); this.$header.html(html.join('')); }, initBody: function(data, append) { var that = this, html = []; $.each(data || this.options.data, function(i, item) { html.push(''); $.each(that.header.fields, function(j, field) { var value = item[field]; if (typeof that.header.formatters[j] === 'function') { value = that.header.formatters[j](value, item); } html.push('' + value + ''); }); html.push(''); }); this.$body[append ? 'append' : 'html'](html.join('')); }, load: function(data) { this.initBody(data); }, append: function(data) { this.initBody(data, true); } }; $.fn.bootstrapTable = function() { var option = arguments[0], args = arguments, value, allowedMethods = ['load', 'append']; this.each(function() { var $this = $(this), data = $this.data('bootstrapTable'), options = $.extend({}, $.fn.bootstrapTable.defaults, typeof option === 'object' && option); if (!data) { data = new Table($this, options); $this.data('bootstrapTable', data); } if (typeof option === 'string') { if ($.inArray(option, allowedMethods) < 0) { throw "Unknown method: " + option; } value = data[option](args[1]); } else { data.init(); } }); return value ? value : this; }; $.fn.bootstrapTable.defaults = { class: 'table table-striped table-bordered', columns: [], data: [] }; })(jQuery);