繁体   English   中英

数据表:使用JQuery更改所选单元格的值

[英]DataTables: Change value of selected cell using JQuery

我有一个从数据库填写的数据表。 我想更改所选单元格的值。

我不知道如何通过使用单元格和行索引来更改单元格的值。 我怎样才能做到这一点?

这就是我所拥有的:

  $('#dtBasicExample').on('click', 'tbody td', function() {

  var table = $('#dtBasicExample').DataTable();

  //Content I want to insert i the cell
  var NewValue= 'NewValue';

  //get cell index
  var CellIndex=table.cell( this ).index().columnVisible;

  //get row index
  var RowIndex= table.cell( this ).index().row;
})

要更改单元格中的数据,您需要DataTables API中的cell().data()函数: https : //datatables.net/reference/api/cell().data()

$(document).ready(function() {
  var table = $('#example').DataTable();
  $('#example tbody').on('click', 'td', function() {
    var colIndex = table.cell(this).index().column;
    var rowIndex = table.cell(this).index().row;
    table.cell(rowIndex, colIndex).data("new")
  });
});

一个更简单的方法:

$(document).ready(function() {
  var table = $('#example').DataTable();
  $('#example tbody').on('click', 'td', function() {
     table.cell(this).data("new");
   });
});

带有演示:

 $('#example').on('click', 'td', function() { var table = $(this).closest('table').DataTable(); table.cell(this).data("new"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" /> <p>Click any cell and check how we simply change it</p> <table id="example" class="display" style="width:100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Numero</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>155555</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>1</td> <td>2009/01/12</td> <td>$86,000</td> </tr> </tbody> <tfoot> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>1</td> <td>2009/01/12</td> <td>$86,000</td> </tr> </tfoot> </table> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM