如何在JS数据表中查找和更新特定记录

时间:2019-02-12 08:39:58

标签: javascript html datatables

我需要遍历datatable,找到具有特殊ID的记录,并对其进行更新(仅此记录)。

<table id="data_tables">
<thead>
    <tr>
        <td value="id">id_value</td>
        <td>Name</td>
        <td>Surname</td>
    <tr>      
</thead>
<tbody>
    <!-- Datarow 1 -->
    <tr>
        <td value="1">1</td>
        <td>John</td>
        <td>Wayne</td>
    </tr>
    <!-- Datarow 2 -->      
    <tr>
        <td value="2">2</td>
        <td>Clark</td>
        <td>Kent</td>
    </tr>
    <!-- Datarow 3 -->      
    <tr>
        <td value="3">3</td>
        <td>John</td>
        <td>Romero</td>
    </tr>
</tbody>
</table>    

和js代码。它必须是基于datatble的,因为标准循环将不适用于数据表分页(或者至少对我而言不起作用)。

    var counter = 0; //to tell me if rows numer is fine

    var table = $('#data_tables').DataTable(); //to grab anchor to datatable again

    //datatable way
    table.rows().every( function () {
        counter = counter + 1;
        //I don't know how to adress current row in a loop in datatable api     
        if(current_row.value_or_content == 10){

          current_row[1].value = 'New Name';
          current_row[1].value = 'New Surname';

        }

    } );

    alert(counter); //that is why I know that looping works ok
    table.draw(); //to keep filters ok

这是我尝试过的方法,但是无论如何还是不错的。甚至可能更好而不会循环(如果数据表中有很多数据,速度问题吗?)

2 个答案:

答案 0 :(得分:2)

您可以在rows().every() api的函数回调中传递其他参数。使用rowIdx监视并检查表行的索引,然后将其删除。

如果要访问行的数据,可以使用this.data()。它将返回一个包含行数据的数组。例如,如果当前行是第一行,则返回的数据应为:

[
"1",
"John",
"Wayne"
]

$(document).ready(function() {
  const table = $('#data_tables').DataTable(); //to grab anchor to datatable again

  //datatable way
  table.rows().every(function(rowIdx, tableLoop, rowLoop) {
    // The checks the id of the current row
    if (this.data()[0] === "1") {

      console.log(`This is row number ${rowIdx+1}`);
      console.log(`This is this row's data:`);
      console.log(this.data());
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<table id="data_tables" cellspacing="1">
  <thead>
    <tr>
      <th value="id">id_value</th>
      <th>Name</th>
      <th>Surname</th>
    </tr>
  </thead>
  <tbody>
    <!-- Datarow 1 -->
    <tr>
      <td value="1">1</td>
      <td>John</td>
      <td>Wayne</td>
    </tr>
    <!-- Datarow 2 -->
    <tr>
      <td value="2">2</td>
      <td>Clark</td>
      <td>Kent</td>
    </tr>
    <!-- Datarow 3 -->
    <tr>
      <td value="3">3</td>
      <td>John</td>
      <td>Romero</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:1)

您不需要完成所有繁琐的HTML手写操作,您可以使用javascript对象来获取表的内容(这是我在以下示例中所做的事情)。

是的,在DataTables行上有一个嵌入式迭代器,它是every()方法。

基本上,您需要做的是获取必要的记录,进行修改,rows().remove()旧记录,row.add()新记录,然后重新draw()

这是演示

//Define source data
var dataSrc = [
  {id:1, name: 'John', lastname: 'Wayne'},
  {id:2, name: 'Clark', lastname: 'Kent'},
  {id:3, name: 'John', lastname: 'Romero'},
];
//Define DataTable object
var dataTable = $('#data_tables').DataTable({
  sDom: 't',
  data: dataSrc,
  columns: [
    {title: 'id', data: 'id'},
    {title: 'name', data: 'name'},
    {title: 'lastname', data: 'lastname'},
  ]
});
//Create dynamically interface for editing
$('body').append(`
<div id="editingform" style="display:none">
  <select id="idselector">
    <option value="" disabled selected>id</option>
  </select>
</div>
`);
//Append fields that correspond to table columns minus id column
dataTable.columns().every(function(){
  if(this.dataSrc() == 'id') return;
  $('#editingform').append(`
    <input class="fieldsinput" datasrc="${this.dataSrc()}" placeholder="${this.dataSrc()}"></input>
  `);
});
//Populate id select with possible options
$.each(dataTable.column(0).data(), function(index, value){
  $('#idselector').append(`
    <option value="${value}">${value}</option>
  `);
});
//Append 'Edit' button and make editing form visible
$('#editingform').append(`<button id="editbutton">Edit</button>`);
$('#editingform').show();
//Listen for id selection and populate input fields
$('#idselector').on('change', function(){
  //Grab row with matching 'id' value
  let rowData = dataTable.rows(`:has(td:eq(0):contains('${$(this).val()}'))`).data()[0];
  //Update input fields
  $.each(rowData, function(index, value){
    $(`input[datasrc="${index}"]`).val(value);
  });
})
//Change source data upon 'Edit' button click and redraw dataTable
$('#editbutton').on('click', function(){
	//Prepare new entry
	let newEntry = {id:$('#idselector').val()};
	$.each($('.fieldsinput'), function(){
		newEntry[$(this).attr('datasrc')] = $(this).val();
	});
	//Remove corresponding column, add new and redraw
	dataTable.rows(`:has(td:eq(0):contains("${newEntry.id}"))`).remove();
	dataTable.row.add(newEntry);
	dataTable.draw();
});
<!doctype html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="data_tables"></table>
</body>

相关问题