javascript - 如何在数据表的每一行中添加编辑/删除按钮
问题描述
我创建了一个数据表,现在我需要编辑和删除表中的记录,所以我想在年份列旁边添加删除和编辑按钮。该列名应该作为操作。
索引.html
<!doctype html>
<html class="no-js" lang="zxx">
<head>
<title>index</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="fontawesome-free-5.14.0-web\css\all.css">
</head>
<body>
<div class="adapt_area">
<div class="container">
<table id="newexample" class="table table-striped table-bordered table-light" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Subject</th>
<th>Year</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#newexample').dataTable({
"bProcessing": true,
"sAjaxSource": "fetchdata.php",
"aoColumns": [
{ mData: 'title' } ,
{ mData: 'name' },
{ mData: 'year_name' }
],
});
});
</script>
</html>
获取数据.php
<?php
require 'db_connection.php';
$query = "SELECT notes.title,subject.name,year.year_name from notes
INNER JOIN subject ON notes.subject=subject.id
INNER JOIN year ON subject.year=year.id";
$result = $conn->query($query);
$data=array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$data[] = $row;
}
$results = ["sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data ];
echo json_encode($results);
?>
解决方案
您可以在文档中使用此示例:
$(document).ready(function() {
var table = $('#newexample').dataTable( {
"ajax": "fetchdata.php",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button id="edit">edit</button>"
} ]
} );
$('#newexample tbody').on( 'click', '#edit', function () {
//the job
} );
} );
所以要检索数据,你可以使用这个:
var data = table.row(this).data();
和 data 是访问数据使用的数组:
data[0],data[1] ....
推荐阅读
- python - 错误:没有名为“sklearn.tree.tree”的模块
- ruby-on-rails - 反应:尝试将选择设置为下拉选项
- node.js - 启动新应用程序时,有什么方法可以在 Electron JS 中获取钩子或事件
- javascript - 问题:javascript switch case 不适用于我的 var
- sharepoint - SharePoint 搜索不适用于隐藏库
- javascript - 没有 Node.Js 的 CkEditor simpleupload 适配器
- python - unique() 没有显示 Python 中的所有值
- java - java - 在具有列表返回类型的Java查询中调用参数值?
- azure - 如何使“Azure 服务总线”消息由实例池中的单个服务器实例处理?
- php - 获取替换前的字符串