乐趣区

关于javascript:javascript动态合并纵向单元格

合并相邻行内容雷同的单元格。

<table>
    <tr *ngFor="let item of data">
      <td *ngIf="item.nameRowspan != 0" [attr.rowspan]='item.nameRowspan'>{{item.name}}</td>
      <td *ngIf="item.sexRowspan != 0" [attr.rowspan]='item.sexRowspan'>{{item.sex}}</td>
      <td>{{item.age}}</td>
    </tr>
  </table>
var data =  [{name: 'dwj', sex: '女', age: 20},
      {name: 'dwj', sex: '男', age: 20},
      {name: 'dwq', sex: '女', age: 20},
      {name: 'other', sex: '女', age: 20}
    ];
rowspanFun(data, ['name', 'sex']);
function rowspanFun(data, nameList) {for (var i = 0; i < nameList.length; i++) {var name = nameList[i];
      var startRow = 0;
      var endRow = data.length;
      var mergeNum = 1;
      if (endRow != 1) {for (var j = startRow; j < endRow; j++) {if (j == endRow - 1) { // 判断是否是最初一个元素
            if (startRow == endRow - 1) {data[j][name + 'Rowspan'] = 1;
            }
          } else {if (data[startRow][name] == data[j + 1][name]) {data[j + 1][name + 'Rowspan'] = 0;
              mergeNum = mergeNum + 1;
              data[startRow][name + 'Rowspan'] =mergeNum;
            } else {
              startRow = j + 1;
              if (mergeNum > 1) {data[startRow][name + 'Rowspan'] = 1;
              } else {data[j][name + 'Rowspan'] = 1;
              }
              mergeNum = 1;
            }
          }
        }
      } else {data[0][name + 'Rowspan'] = 1;
      }
    }
    return data;
  }

退出移动版