2009-09-02 66 views
1

我在寫一個JavaScript函數來突出顯示單擊單元格的行和列。此功能必須考慮到先前行中使用rowspan的單元格向下突出到選定行中 - 因爲這會導致單元格索引與「明顯」索引不同。 I.E.表格第二列中的每個單元格不一定有cellIndex==1FireFox/JQuery/Dom:不返回'rowIndex

爲了補償,我寫了下面的函數來計算每個受影響的單元格的「偏移量」。

function OffsetCells($tbody) { 
// if already indexed, we don't need to re-do it 
if (!$tbody.data('isOffset').value) { 
    // set offset for all cells to zero 
    $tbody.find('td').data('offset', { value: 0 }); 
    // it's not already indexed, so get the cells that span multiple rows 
    // capitalization of 'rowSpan' is important for IE 
    var $rowSpanners = $tbody.find('td[rowSpan!=1]'); 
    $rowSpanners.each(function() { 
     var $rowSpanningCell = $(this); 
     // we need to select all the cells to the 'apparent' right of this cell, 
     // so we need this cell's apparent position 
     // multiplying by one is easier than parseInt() to ensure conversion 
     $rowSpanningCell.data('apparentIndex', { value: this.cellIndex * 1 +  $rowSpanningCell.data('offset').value }); 
     // we also need to know what row this cell is in 
/*???*/  $rowSpanningCell.data('rowIndex', { value: $rowSpanningCell.parent('tr').get(0).rowIndex }); 
     // down to business: 
     $tbody.parent('table') // get the whole table 
     .find('tr')   // get all the rows in the table 
     .slice($rowSpanningCell.data('rowIndex').value + 1, $rowSpanningCell.data('rowIndex').value + this.rowSpan) // narrow selection to the applicable rows 
     .find('td')    // get the cells in the chosen rows 
     .filter(function(index) { // get the cells to the apparent right of this one. 
      return index + $(this).data('offset').value >= $rowSpanningCell.data('apparentIndex').value; 
     }).each(function() { 
      $(this).data('offset', { value: $(this).data('offset').value + 1 }); 
     }); 
    }); 
    $tbody.data('isOffset', { value: true }); 
} 
} 

這段代碼可以在IE中很好地工作,但在/*???*/這條線上默默無聞。我已經縮小到$rowSpanningCell.parent('tr').get(0).rowIndex部分。我已經嘗試了所有我能想到的東西,並且仍然無法讓它返回值rowIndex。當我將代碼更改爲alert($rowSpanningCell.parent('tr').get(0).nodeName)時,我得到預期的<TR>,所以我知道我的選擇是正確的。該行的每個其他屬性的其他每個值似乎都會返回正常 - 但rowIndex只是使代碼冷卻。

回答

1

您可以嘗試

$rowSpanningCell.parent('tr').prevAll().length

,這將給你的索引

+0

解決此問題的另一種方式,我發現是使用$ rowSpanningCell.parent()[0] .sectionRowIndex。 SectionRowIndex受支持,並且都適用於兩者。 – 2009-09-02 21:01:58

+0

但它比上面更難讀 – redsquare 2009-09-02 21:11:57