tableMerge.js 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * 列合并工具类
  3. * 调用eg : fnMergeRowCell($("[name=maintbody]"), [0, 1, 2], 0);
  4. * maintbodyObj : 需要合并列的表格对象(tbody),必填
  5. * limitRowOrRowIndexs : 需要合并的列,必填
  6. * basicIndex : 以哪一列为基准,非必填,如果没有可以选择null
  7. */
  8. var fnMergeRowCell = function(maintbodyObj, limitRowOrRowIndexs, basicIndex) {
  9. var limitRow = null //从0~n列
  10. var limitRowIndex = null; //具体限制某列,如[0,4,5]
  11. if(limitRowOrRowIndexs == undefined || limitRowOrRowIndexs == null) {
  12. limitRow = null;
  13. limitRowIndex = null;
  14. } else {
  15. if($.isArray(limitRowOrRowIndexs)) {
  16. limitRowIndex = limitRowOrRowIndexs;
  17. limitRow = null;
  18. } else {
  19. limitRowIndex = null;
  20. limitRow = limitRowOrRowIndexs;
  21. }
  22. }
  23. if(basicIndex == null || basicIndex == undefined){
  24. basicIndex = null;
  25. }
  26. /**
  27. * 名称说明
  28. * 1. 主合并对象:设置rowspan的td
  29. * 2. 子合并对象:被隐藏的td
  30. *
  31. * 实现原理
  32. * 1. 每行扫描,拿当前行和下一行做对比,如果值为一致,标记为主合并对象(在标记前要判断是否为主标记对象,如果为子标记对对象进行data-ishide 标记 ),
  33. * 2. 下一行自动标记上主合并对象的 data-pid
  34. */
  35. var callAttr = "data-main";
  36. var dataPidKey = "data-cid";
  37. var $tbody = $(maintbodyObj);
  38. var trs = $tbody.find("tr");
  39. for(var i = 0; i < trs.length; i++) {
  40. var $cr = $(trs[i]);
  41. var $nr = $(trs[i + 1]);
  42. var $crtd = $cr.find("td"); //当前行下面的td
  43. var $nrtd = $nr.find("td"); //下一行下面的td
  44. if(limitRow == null) {
  45. limitRow = $crtd.length;
  46. }
  47. for(var r = 0; r < limitRow; r++) {
  48. if(null != limitRowIndex) {
  49. if(limitRowIndex.indexOf(r) == -1) {
  50. continue;
  51. }
  52. }
  53. var $crtdRow = $($crtd[r]);
  54. var $nrtdRow = $($nrtd[r]);
  55. var $crtdbRow = basicIndex == null ? "":$($crtd[basicIndex]);
  56. var $nrtdbRow = basicIndex == null ? "":$($nrtd[basicIndex]);
  57. //当前行对应的单元格的值 和 下一行对应的单元格的值相同
  58. if($crtdRow.html() == $nrtdRow.html() && $crtdbRow.html() == $nrtdbRow.html()) {
  59. var dataId = $crtdRow.attr(dataPidKey);
  60. //如果为隐藏,则代表着这个已经是被合并的了,需要拿到data-pid
  61. if($crtdRow.attr(callAttr) != "false") {
  62. dataId = "coordinate_" + i + "_" + r;
  63. $crtdRow.attr(callAttr, "true").attr(dataPidKey, dataId); //标记主要主合并对象
  64. }
  65. $nrtdRow.attr(callAttr, "false").attr(dataPidKey, dataId);
  66. $nrtdRow.hide();
  67. }
  68. }
  69. }
  70. $tbody.find("[" + callAttr + "=true]").each(function(i, _d) {
  71. var dataPid = $(_d).attr(dataPidKey);
  72. $(_d).attr("rowspan", $tbody.find("[" + dataPidKey + "=" + dataPid + "]").length).addClass("center");
  73. });
  74. }