一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

HTML Table空白单元格补全实现方法

时间:2020-08-04 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下HTML Table空白单元格补全实现方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

所谓宫格,就是说表格,3 行x 4 列 = 共12 单元格。如果只有 10 个产品,就只能填充表格 10 个单元格,其余的为空白。虽然空白,但也要渲染 元素,不然 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;
  }
   
  /**
   * 为每个值加个 。若满一行加一个 
   * @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 '' + html + '
'; // var table = document.createElement('table'); // table.innerHTML = html; // table.border="1"; // document.body.appendChild(table); } }); });

2019-5-18 JSTL 的方式:

<%
 // 空白单元格补全
 String tds = ""; int maxTds = 9; 
 List list = (List)request.getAttribute("list");
 for(int i = 0; i < (maxTds - list.size()); i++ ) {
  tds += "";
 }
 
 request.setAttribute("tds", tds);
%>
  
     
   
     ${tds}
    

${item.name}----${totalCount}

热门栏目