【发布时间】:2013-01-15 17:20:34
【问题描述】:
我需要在使用下面的代码时向 DataTables 中新添加的单元格添加一个 id、类和一个事件。我怎样才能做到这一点?
var rtn = oTable.fnAddData(['Cell1Value', 'Cell2Value', 'Cell3Value']);
我试图在单击这个新添加的单元格时触发一个 javaScript 函数。
【问题讨论】:
标签: jquery datatables
我需要在使用下面的代码时向 DataTables 中新添加的单元格添加一个 id、类和一个事件。我怎样才能做到这一点?
var rtn = oTable.fnAddData(['Cell1Value', 'Cell2Value', 'Cell3Value']);
我试图在单击这个新添加的单元格时触发一个 javaScript 函数。
【问题讨论】:
标签: jquery datatables
这有点笨拙,但你可以通过这样做来实现你想要的。
HTML
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">
<thead>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</thead>
<tbody>
<tr class="odd gradeX">
<td>Trident</td>
<td>Internet
Explorer 4.0</td>
<td>Win 95+</td>
<td class="center"> 4</td>
<td class="center">X</td>
</tr>
<tr class="even gradeC">
<td>Trident</td>
<td>Internet
Explorer 5.0</td>
<td>Win 95+</td>
<td class="center">5</td>
<td class="center">C</td>
</tr>
<tr class="odd gradeA">
<td>Trident</td>
<td>Internet
Explorer 5.5</td>
<td>Win 95+</td>
<td class="center">5.5</td>
<td class="center">A</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</tfoot>
</table>
<button id="addnewrow">Add New Row</button>
JS
$('#addnewrow').click(function(){
//add row
var newRow = $('#example').dataTable().fnAddData( [
"1",
"2",
"3",
"4",
"5"]
);
//change cell attributes
var oSettings = dataTable.fnSettings();
var nTr = oSettings.aoData[ newRow[0] ].nTr;
$('td', nTr)[0].setAttribute( 'id', 'newid1' );
$('td', nTr)[1].setAttribute( 'id', 'newid2' );
$('td', nTr)[2].setAttribute( 'id', 'newid3' );
$('td', nTr)[3].setAttribute( 'id', 'newid4' );
$('td', nTr)[4].setAttribute( 'id', 'newid5' );
});
然后你可以简单地用类似这样的方式委托你的新 id 或类的点击
$('table').delegate('#newid1','click', function(){
alert('clicked on new cell 1')
})
【讨论】: