在最初自学 Web 开发的时候,那时没有所谓的 DIV/CSS 布局,一概 Table 布局的天下。当时有个问题就来了,如何补全宫格空白的单元格呢?——这是我在弄公司产品页头痛的问题。因为我不是学程序出身的,碰到这稍带算法的问题,就束手无策了,呵呵。顺带说说,记得分页的算法还折腾了我一下呢。
所谓宫格,就是说表格,3 行x 4 列 = 共12 单元格。如果只有 10 个产品,就只能填充表格 10 个单元格,其余的为空白。虽然空白,但也要渲染
元素,不然 table 会看起来会走样。写死当然可以,但问题 table 都是经过 ASP 动态渲染的。所以怎么计算,怎么该显示空白 td 就是个问题。我当时想了几个方法,回想起来很当然很不是合理,总之都是死马当活马医……能显示就行……呵呵。
后来到了 DIV/CSS 时代,Table 遭弃用。于是该算法也没关心了。——再后来一次项目中,发现 table 布局仍然适用的,于是就琢磨了一下这小问题。用 JS 动态控制的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | /** * @class renderTable * 输入一个数组 和 列数,生成一个表格 table 的 markup。 * @param {Array} list * @param {Number} cols * @param {Function} getValue */ define( function (require, exports, module) { module.exports = function (list, cols, getValue){ this .list = list; this .cols = cols || 5; this .getValue = getValue || this .getValue; } module.exports.prototype = ( new function (){ this .render = function (list){ list = list || this .list; var len = list.length ; var cols = this .cols; // 位数 var rows; var remainder = len % cols; var htmls = []; rows = len / remainder; if (remainder == 0){ // 可整除 无余数 直接处理 list.forEach(addTr.bind({ cols : cols, htmls: htmls, getValue : this .getValue })); } else { // 处理余数部分 var remainnerArr = list.splice(list.length - remainder); list.forEach(addTr.bind({ cols : cols, htmls: htmls, getValue : this .getValue })); // 填空位 var emptyArr = new Array(cols - remainnerArr.length); emptyArr = emptyArr.join( 'empty' ); emptyArr = emptyArr.split( 'empty' ); // 余数部分 + 空位 remainnerArr = remainnerArr.concat(emptyArr); if (remainnerArr.length != cols){ throw '最后一行长度错误!长度应该为' + cols; } remainnerArr.forEach(addTr.bind({ cols : cols, htmls: htmls, getValue : this .getValue })); } return addTable(htmls.join( '' )); } /** * 默认的获取显示值的函数。一般要覆盖该函数。 * @param {Mixed} * @return {String} */ this .getValue = function (data){ return data; } /** * 为每个值加个 。若满一行加一个 * @param {Mixed} item * @param {Number} i * @param {Array} arr */ function addTr(item, i, arr){ var html = '' + this .getValue(item) + '' ; if (i == 0){ html = '' + html; } else if ((i + 1) % this .cols == 0 && i != 0){ html += '' ; } else if (i == arr.length){ html += '' ; } this .htmls.push(html); } /** * * @param {String} html */ function addTable(html){ return ' |
‘;
// var table = document.createElement(‘table’);
// table.innerHTML = html;
// table.border=”1″;
// document.body.appendChild(table);
}
});
});
大大们可能觉得这可是一闪而过就有思路的问题……但我那时毕竟是在转行……稍有点“技术含量”的问题都成了我的拦路虎……
2019-5-18 JSTL 的方式:
1 2 3 4 5 6 | list = (List>)request.getAttribute("list"); for(int i = 0; i "; } request.setAttribute("tds", tds); %> |
${item.name}—-${totalCount} |
到此这篇关于HTML Table 空白单元格补全的实现方法的文章就介绍到这了,更多相关HTML Table 空白单元格补全内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章,希望大家以后多多支持IT俱乐部!