2012-12-25 17 views
0

請在這裏看到一個演示。 http://jsfiddle.net/wgstudio/CqNfZ/2/如何知道合併行或列的html表的實際列和行索引

我想合併單元格(0,0)和單元格(1,0)在html talbe,它工作在一個常規的表。

該代碼isbelow。

 function() { 
      var table = $("#table1"); 

      var rowIndex = 0; 
      var colIndex = 0;     
      var actionCell =$($(table.children().children()[rowIndex]).children()[colIndex]); //Cell1 
      var tr = table.children().children()[rowIndex + 1]; 
      var toBeRemoved = $($(tr).children()[colIndex]);//Cell4 
      toBeRemoved.remove(); 
      rowSpan = toBeRemoved.attr("rowSpan") == undefined ? 1 : parseInt(toBeRemoved.attr("rowSpan"), 10); 
      actionCell.attr("rowspan", (actionCell.attr("rowSpan") == undefined ? 1 : parseInt(actionCell.attr("rowSpan"), 10)) + rowSpan); 
     } 

但如果表是這樣的:

<table id="table2" style=" width: 100%;"> 
     <tr> 
      <td rowspan="2">cell_1</td> 
      <td rowspan="2">cell_2cell_5</td> 
      <td>cell_3</td> 
     </tr> 
     <tr> 
      <td>cell_6</td> 
     </tr> 
     <tr> 
      <td>cell_7</td> 
      <td>cell_8</td> 
      <td>cell_9</td> 
     </tr> 
    </table> 

(0,0),(0,1)合併的細胞,當我想合併(0,0) 「小區1」 和(2,0)「Cell7」,如何通過js代碼找到「cell 7」?

希望我解釋清楚。

非常感謝。

比爾

+0

這將如何從用戶角度在更真實的世界環境中工作?您的簡化演示僅適用於第一行和第二行。可以給你更多靈活的解決方案,如果underrstand將如何實施 – charlietfl

回答

0

您所遇到的主要問題是,一旦行跨度被添加到細胞時,它拋出了排索引。如果一行中的單元格具有rowspan=3,則同一列中下一個單元格的row indexcurrentRowIndex + 3

這是你需要的一個很好的開始。

$("#button2").click(function() { 
    /* hard code a cell to start with*/ 
    var actionCell = $('td:first'); 

    var toBeRemoved = findNextCell(actionCell); 

    combineSpans(actionCell, toBeRemoved) 

    /* remove merged*/ 
    toBeRemoved.remove(); 

}); 

function combineSpans(actionCell, toBeRemoved){ 
    var actionSpans = getCellSpans(actionCell); 
    var nextSpans = getCellSpans(toBeRemoved); 
    /* add colspan and rowspan for both cells to apply to actionCell*/ 
    var newSpans = { 
     rowspan: actionSpans.rowSpan + nextSpans.rowSpan, 
     colspan: actionSpans.colSpan + nextSpans.colSpan 
    } 
    /* adjust actionCell colspan/rowspan*/ 
    actionCell.attr(newSpans); 

} 

function findNextCell($cell) { 

    var cellIndex = $cell.index(); 
    var rowSpan = $cell.attr("rowspan") || 1; 
    var rowIndex = $cell.closest('tr').index(); 
    var nextRow = $cell.closest('table').find('tr').eq(1 * rowSpan + rowIndex); 
    return nextRow.find('td').eq(cellIndex); 

} 


function getCellSpans($cell) { 
    var obj = {} 
    obj.rowSpan = parseInt($cell.attr("rowspan") || 1, 10); 
    obj.colSpan = parseInt($cell.attr("colspan") || 1, 10); 
    return obj; 

} 

DEMO:http://jsfiddle.net/CqNfZ/7/

編輯:剛剛意識到我combineSpans邏輯需要修改。將2個單元colspan加在一起會導致問題

+0

嗨charlietfl,我的演示代碼也是硬編碼,試圖讓我的問題容易被理解。你的回答真的幫了我很多。非常感謝你和新年快樂! :) – Bill

相關問題