代码之家  ›  专栏  ›  技术社区  ›  baron_bartek

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

  •  1
  • baron_bartek  · 技术社区  · 6 年前

    我需要循环通过 datatable ,找到一个specyfic 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的,因为标准循环无法与datatable分页一起工作(或者至少它在我的表单中不工作)。

        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 回复  |  直到 6 年前
        1
  •  1
  •   Ekown    6 年前

    您可以在函数回调中为 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());
        }
      });
    });
    <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>
        2
  •  2
  •   Curr195    6 年前

    您不需要做所有冗长的HTML手写,您可以使用javascript对象来源代码表(这是我在下面的示例中所做的)。

    没错,数据表行上有一个嵌入的迭代器 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>