Reputation: 4919
I have a simple html table that looks like so:
I would like to modify it into this:
I wrote simple plugin to do the job:
(function ($) {
var settings;
$.fn.splitTable = function (options) {
var $this = this;
//options
settings = $.extend({}, defaults, options);
$this.filter("table").each(function () {
//body
var table = $(this);
var $tds = table.find('tbody td');
var k, l;
for (k = 0, l = Math.ceil($tds.length / settings.columns); l < $tds.length; k++, l++)
$($tds[k]).parent().append($tds[l]);
//header
var $ths = table.find('thead th');
for (var i = 0; i < settings.columns - 1; i++) {
$ths.each(function () {
table.find('tr:first').append(this.outerHTML);
});
}
});
return $this;
};
var defaults = {
columns: 2
};
})(jQuery);
Here is jsFiddle sample: http://jsfiddle.net/Misiu/Tsqvj/
This works almost as expected, but jshint gives me error inside look where I clone header:
Don't make functions within a loop.
Second thing is speed. With small tables this works fine, but with large tables (rows>2k) and on old browsers this freezes browser for a while.
I know that I could ask on codereview, but my code isn't working as expected. If it will work I'll try to improve it and then I'll ask on codereview.
Upvotes: 0
Views: 226
Reputation: 330
As the jshint error messages says, you are defining a function within a loop:
for (var i = 0; i < settings.columns - 1; i++) { /* THIS IS THE LOOP */
$ths.each(function () { /* THIS IS THE FUNCTION */
table.find('tr:first').append(this.outerHTML);
});
}
The error can easily be fixed by defining the function before the loop, like this:
var appendToTable = function () {
table.find('tr:first').append(this.outerHTML);
}
for (var i = 0; i < settings.columns - 1; i++) {
$ths.each(appendToTable);
}
Upvotes: 1