2014-01-29 93 views
0

請參閱此jsfiddle
我的設置有以下兩個表格:simTable = datatable-simf-simresTable = datatable-simf-res識別並比較兩個不同表格中的兩行

我試圖在resTable中添加一行,每次用戶在simTable的行中選擇(點擊),這個工作很好。但是,當用戶取消選擇該行時,應將其從simTable中刪除。

resTable = $('#datatable-simf-res').dataTable({}); 
simTable = $('#datatable-simf-sim').dataTable({}); 

$('#datatable-simf-sim tr').click(function() { 
    if ($(this).hasClass('row_selected')) { 
     $(this).removeClass('row_selected'); 
     var uniqueid = $(this).closest('tr').children('td:eq(0)').text(); 

     $('#datatable-simf-res tr td').each(function() { 
      if ($(this).text() === uniqueid) { 
       var rowindex = $(this).closest('tr').index(); 
       resTable.fnDeleteRow(rowindex); 
      } 
     }); 

    } else { 
     $(this).addClass('row_selected'); 

     var rows = []; 
     $(this).closest('tr').find("td").each(function (cell, v) { 
      rows.push($(this).text()); 
     }); 
     resTable.fnAddData(rows); 
    } 
    resTable.fnDraw(); 
}); 

當你用的jsfiddle玩(只需單擊行一堆倍),你會看到,它會留下行不動,或刪除了錯誤的行。我認爲這與我在resTable中確定一行的方式有關,因爲這對我來說是最大的瓶頸。

那麼我如何成功識別和比較兩個不同表中的兩行?
非常感謝。

+0

小提琴在Chrome中似乎對我很好。 – sjy

回答

0

雖然小提琴似乎沒什麼問題,以刪除該行更清潔的方法是:

// iterate over rows, not all cells 
$('#datatable-simf-res tr') 
    .filter(function() { 
    // check if the first column contains the unique ID 
    return $(this).find('td:first').text() === uniqueid 
    }) 
    .each(function() { 
    // 'this' is the current DOM element, inside .each() 
    resTable.fnDeleteRow(this) 
    }); 

(該DataTables APIfnDeleteRow可以接受的指標或<tr>元素。)

+0

謝謝。我原來的方法在Firefox中顯示不一致的結果,你的工作很好,看起來更乾淨。謝謝! –