首页 > 解决方案 > 向数据表行添加 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);

  });
});

标签: javascriptjquerydatatables

解决方案


您可以将 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>


推荐阅读