2010-09-20 27 views
2

我有一個表,設置出像:jQuery的數據表更新單元

<table id="myTable"> 
    <thead> 
    <tr> 
     <td><input type="checkbox" id="selectall" /></td> 
     <td>Column 1</td> 
     <td>Column 2</td> 
     <td>Column 3</td> 
     <td>Column 4</td> 
     <td>Column 5</td> 
    </tr> 
    </thead> 
    <tbody> 
    </tbody> 
</table> 

然後,JavaScript的:

var myTable = jQuery('#myTable').dataTable({ 
    /* options */ 
}); 

// Ajax request to populate: 
jQuery.get('script.php', function(data){ 
    eval("rows="+data); 
    for(var i=0;i<rows.length;i++){ 
     myTable.fnAddData([ 
      "<input type=\"checkbox\" id=\""+rows[i].uniqueID+"\" />", 
      rows[i].col1Txt, 
      rows[i].col2Txt, 
      rows[i].col3Txt, 
      rows[i].col4Txt, 
      rows[i].col5Txt ]); 
    } 
}); 

現在,我有在此基礎上更新表麻煩複選框是選擇:

我想更新檢查每一行中的第5個單元格。我正在使用fnUpdatefnGetPositionhttp://www.datatables.net/api)的組合。

fnGetPosition預計tdtr元素,所以我想我只是抓住了家長的複選框的td

var checkBoxes = jQuery('td > input:checked', myTable); 
for(var i=0;i<checkBoxes.length;i++){ 
    var parentTD = jQuery('#'+checkBoxes[i].id).parent(); //seems wrong? 
    var pos = myTable.fnGetPosition(parentTD); 
    //alert(pos[0]); 
    myTable.fnUpdate('Updated text', pos[0], 5); 
} 

但是我必須做parentTD因爲pos錯誤似乎永遠不會保存一個值。

任何想法?

回答

7

你可以使用each函數遍歷一個jQuery對象,它比使用for循環更容易。

此外,我認爲你可以optomise你的選擇器讓你的td元素,而不是geting的檢查輸入。

這將是一個更高性能,因爲它應該刪除每個操作中的2個選擇器。 我還沒有嘗試過,但這樣的事情應該工作

var checkBoxes = jQuery('td:has(input:checked):not(#selectall)', myTable); 
checkboxes.each(function(){ 
    var pos = myTable.fnGetPosition($(this)); // Im not familiar with the plugin so the extra $() might be overkill 
    alert(pos) // maybe run this alert again, check if you get back an object/value? use firebug to debug and see its value? 
    myTable.fnUpdate('Updated text', pos[0], 5); 
}); 
+0

不錯,一個工作。我知道每個(),我都無法收集我有限的jQuery知識來獲取所有這些tds。非常感謝。 – tombh 2010-09-20 15:03:53

+0

@tombh:沒問題,很高興我能幫上忙。 – DannyLane 2010-09-20 15:39:20

+0

這是如何與新的API? – 2016-10-24 17:57:36