这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
下面小编就为大家带来一篇 html Table 空白单元格补全的简单实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
在最初自学 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);
- }
- });
- });
大大们可能觉得这可是一闪而过就有思路的问题…… 但我那时毕竟是在转行…… 稍有点 "技术含量" 的问题都成了我的拦路虎……
来源: http://www.phperz.com/article/17/0526/331221.html