在最初自學 Web 開發的時候,那時沒有所謂的 DIV/CSS 布局,一概 Table 布局的天下。當時有個問題就來了,如何補全宮格空白的單元格呢?——這是我在弄公司產品頁頭痛的問題。因為我不是學程序出身的,碰到這稍帶算法的問題,就束手無策了,呵呵。順帶說說,記得分頁的算法還折騰了我一下呢。
所謂宮格,就是說表格,3 行x 4 列 = 共12 單元格。如果只有 10 個產品,就只能填充表格 10 個單元格,其余的為空白。雖然空白,但也要渲染 <td></td> 元素,不然 table 會看起來會走樣。寫死當然可以,但問題 table 都是經過 ASP 動態渲染的。所以怎麼計算,怎麼該顯示空白 td 就是個問題。我當時想了幾個方法,回想起來很當然很不是合理,總之都是死馬當活馬醫……能顯示就行……呵呵。
後來到了 DIV/CSS 時代,Table 遭棄用。於是該算法也沒關心了。——再後來一次項目中,發現 table 布局仍然適用的,於是就琢磨了一下這小問題。用 JS 動態控制的代碼如下:
/**
* @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;
}
/**
* 為每個值加個 <td></td>。若滿一行加一個 </tr></tr>
* @param {Mixed} item
* @param {Number} i
* @param {Array} arr
*/
function addTr(item, i, arr){
var html = '<td>' + this.getValue(item) + '</td>';
if(i == 0){
html = '<tr>' + html;
}else if((i + 1) % this.cols == 0 && i != 0){
html += '</tr><tr>';
}else if(i == arr.length){
html += '</tr>';
}
this.htmls.push(html);
}
/**
*
* @param {String} html
*/
function addTable(html){
return '<table>' + html + '</table>';
// var table = document.createElement('table');
// table.innerHTML = html;
// table.border="1";
// document.body.appendChild(table);
}
});
});
大大們可能覺得這可是一閃而過就有思路的問題……但我那時畢竟是在轉行……稍有點“技術含量”的問題都成了我的攔路虎……
以上就是小編為大家帶來的HTML Table 空白單元格補全的簡單實現全部內容了,希望大家多多支持~