由于解析课程表的缘故,有如下需求:
1. 将任意表格解析成独立的单元格矩阵【本次博文的缘由】
2. 根据矩阵坐标,确定任意一格的节点
/* 表格-->网格化 标记表格的位置及其对应的节点 */ var Grids = function(tableSelector,cell,row){ var cells = cell;//每行的列数 var rows = row;//每列的行数 var grids = new Array(rows);//行数 var table = document.querySelectorAll(tableSelector)[0]; var tds = table.getElementsByTagName("td"); var array1D = [];//网格的一维数组:方便快速搜索 //网格初始化 for(var i = 0; i < rows; i++){ grids[i] = new Array(cells); for(var j = 0; j < cells; j++){ grids[i][j] = "[" + (i + 1) + "," + (j + 1) + "]"; } } //注入网格单元信息 var colCounter = 0;//统计跨列的个数 var rowCounter = 0; //统计跨行的个数 var cursor = 0; //记录tds的游标 for(var i = 0; i < rows; i++){ for(var j = 0; j < cells; j++){ //一行的各列(跨列问题) if(!(grids[i][j] instanceof HTMLElement)){//未被填充时 for(var k = 0; k < tds[cursor].colSpan; k++){ grids[i][j + k] = tds[cursor]; } for(var m = 0; m < tds[cursor].rowSpan; m++){ grids[i + m][j] = tds[cursor]; } cursor++; } else {//已被填充node时,不作处理 } } } console.log('grids:', grids); return grids; } /** 分析: Text [i,j] index cursor 时间 [0,0] ==> 1 -> [0] ==> [colCounter(0) + rowCounter(0) + 0]; 时间 [0,1] ==> 1 -> [0] ==> [colCounter(0) + rowCounter(0) + 0]; //col:之后才+1 星期一 [0,2] ==> 2 -> [1] ==> [colCounter(1) + rowCounter(0) + 1]; 星期二 [0,3] ==> 3 -> [2] ==> [colCounter(1) + rowCounter(0) + 2]; 星期三 [0,4] ==> 4 -> [3] ==> [colCounter(1) + rowCounter(0) + 3]; 星期四 [0,5] ==> 5 -> [4] ==> [colCounter(1) + rowCounter(0) + 4]; 星期五 [0,6] ==> 6 -> [5] ==> [colCounter(1) + rowCounter(0) + 5]; 星期六 [0,7] ==> 7 -> [6] ==> [colCounter(1) + rowCounter(0) + 6]; 星期日 [0,8] ==> 8 -> [7] ==> [colCounter(1) + rowCounter(0) + 7]; ============================================================================================ 早晨 [1,0] ==> 9 -> [8] ==> [colCounter(1) + rowCounter(0) + 8]; 早晨 [1,1] ==> 9 -> [8] ==> [colCounter(1) + rowCounter(0) + 8];//col:之后才+1 "" [1,2] ==>10 -> [9] ==> [colCounter(2) + rowCounter(0) + 9]; "" [1,2] ==>11 -> [10] ==> [colCounter(2) + rowCounter(0) + 10]; colSpan变化的动因: 已结束了一个引起colSpan的td项 rowSpan变化的动因: cursor变化的动因: */ addEventLoad(function(){//外部小工具:自行忽略 var grids = new Grids("#Table1", 9, 13); },true);