javascript - 向数据表行添加 id
问题描述
每次单击按钮时,我都使用一个函数向我的数据表中添加一个新行。但是,我希望能够为添加的每个新行添加一个行 ID,但由于某种原因,我尝试这样做的方式不起作用。为了测试我的代码是否正常工作,我添加了一个警报,在单击该行时告诉我行 ID。你可以在这里看到页面。下面是我的代码:
$('#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);
});
});
解决方案
您可以将 ID 添加到从 返回的行节点table.row.add
。您可以查看row.add API以获取更多信息,但您可以使用以下示例做您想做的事情
var table = $('#example').DataTable();
var rowNode = table
.row.add( [ 'Fiona White', 'Engineer' ] )
.draw()
.node();
$(rowNode).attr( 'id', 'myCustomID' );
<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>
推荐阅读
- c - 如何从特定索引开始获取 argv
- html - AngularTS如何将HTML中的输入变量设置为真/假?
- python - 前面没有字符串的双小数位数(可能为负数)的 Python 正则表达式
- r - nearZeroVar() 生成意外的整数 (0)
- xamarin.forms - Xamarin Forms Disable NamedSize 字体不起作用
- amazon-web-services - 用于 ECS 和负载均衡器的 Terraform 第一次失败
- c# - 使用验证 @Html.validationmessagefor 未显示自定义验证消息
- javascript - 刷新页面时关闭暗模式
- c - 在指向联合成员的指针之间进行强制转换
- java - 带有Spring Boot的Mongo Pojo,如何获取文档中的数据子集