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

问题描述 投票:1回答:2

我需要遍历qazxsw poi,找到具有特定id的记录,并更新它(只有这一个)。

datatable

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

<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>    

这就是我尝试的方式,但无论如何都会很好。在没有循环的情况下甚至更好(如果在数据表中有大量数据,则会出现速度问题吗?)

javascript html datatables
2个回答
2
投票

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

如果要访问行的数据,可以使用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());
    }
  });
});

1
投票

你不需要做所有繁琐的HTML手写,你可以使用javascript对象来源你的表(这就是我在下面的例子中所做的)。

你是对的,在DataTables行上有一个嵌入式迭代器,它是<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>方法。

你需要做的是,基本上,抓住必要的记录,修改它,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();
});
© www.soinside.com 2019 - 2024. All rights reserved.