每次单击按钮时,我都使用一个函数向我的数据表中添加一个新行。但是,我希望能够为添加的每个新行添加行ID,但由于某种原因,我尝试这样做的方式无法正常工作。为了测试我的代码是否正常工作,我添加了一个警告,告诉我单击该行时的行ID。您可以看到页面here。以下是我的代码:
$('#addRow').on('click', function() {
$('.progress-button .progress-circle').svgDraw(0);
$('.progress-button').on('click', function() {
var $button = $(this);
$(this).addClass('loading');
var $progress = $(this).find('.progress-circle');
var progress = 0;
var intervalId = setInterval(function() {
progress += Math.random() * 0.5;
$progress.svgDraw(progress);
if(progress >= 1) {
clearInterval(intervalId);
//console.log("cleared interval");
$button.removeClass('loading');
if($button.attr('data-result') == "true") {
$button.addClass('success');
setTimeout(function(){ closeNav(); }, 1000);
}
else {
$button.addClass('error');
}
}
}, 500);
// Now that we finished, unbind
$(this).off('click');
var t = $('#mytable').DataTable();
var reference = document.getElementById('reference').value;
var pallets = document.getElementById('pallets').value;
var pieces = document.getElementById('pieces').value;
var location = document.getElementById('location').value;
var carrier = document.getElementById('carrier').value;
var id = document.getElementById('id').value;
setTimeout(function(){ t.row.add( [
reference,
pallets,
pieces,
location,
carrier,
'<center><a href="delete.php?id=' + id + '" onclick="myAlert(' + id + ')" ><i class="fa fa-truck clear" aria-hidden="true"></i></a></center>',
'<center><a><i class="fa fa-pencil-square-o edit" aria-hidden="true"></i></a></center>'
] ).node().id = id;
t.draw( false );
}, 1500);
});
});
答案 0 :(得分:1)
您可以向从table.row.add
返回的行节点添加ID。您可以查看row.add API以获取更多信息,但您可以使用以下示例执行您想要的操作
var table = $('#example').DataTable();
var rowNode = table
.row.add( [ 'Fiona White', 'Engineer' ] )
.draw()
.node();
$(rowNode).attr( 'id', 'myCustomID' );
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
</tr>
</thead>
</table>
&#13;