我使用带有jquery
Datatables的php脚本将数据从Mysql数据库呈现到客户端浏览器。当用户单击“编辑”列中的“更新”按钮时,我想获取该行的单元格值并填写表格,以便用户可以更新信息。主要问题是jquery
on.('click', 'button', function)
不想获取table.row
数据。点击功能仍然有效。
呈现表格的php脚本:
<table id="usert" class="display" style="width:100%">
<thead>
<th>Id</th>
<th>User</th>
<th>Usernames</th>
<th>Email</th>
<th>Employee</th>
<th>Product</th>
<th>Admin</th>
<th>Active</th>
<th>Edit</th>
</thead>
<tbody>
<?php
//Select all users names from database and populate the select tag
include_once './db/dbconnect.php';
include_once './db/website/dbfunc_web.php';
$db = connectBlind();
$users_i = findUsers($db);
$cnt = 0;
if ($users_i != false) {
foreach ($users_i as $key => $value) {
$cnt ++;
echo "<tr>";
echo "<td>".$cnt."</td>";
echo "<td>".$key."</td>";
foreach ($value as $key => $val) {
if ($key === 'emp_priv' || $key === 'prod_priv' || $key === 'admin_priv' || $key === 'active') {
if ($val === 1) {
echo "<td>Yes</td>";
} else {
echo "<td>No</td>";
}
} else {
echo "<td>".$val."</td>";
}
}
echo "<td><button style="."'background-color: #3CB371; border: none; color: white; font-size: 14px; padding: 8px 10px; border-radius: 8px;'".">Update</button></td>";
echo "</tr>";
}
}
?>
jquery函数:
$(document).ready( function () {
$('#usert').DataTable();
});
$('#usert tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
window.alert( data[1]);
} );
我要单击特定“更新”按钮的单个table.row
数据吗?
答案 0 :(得分:1)
您可以使用<tr>
来获取closest()
,然后使用get()
来获取每个索引。
$('button').on('click', function() {
let td = $(this).closest('tr').find('td');
let result = {
id: td.get(0).innerText,
user: td.get(1).innerText,
username: td.get(2).innerText
};
console.log(result)
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<table>
<thead>
<th>Id</th>
<th>User</th>
<th>Usernames</th>
<th>Edit</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Jon</td>
<td>jon_bob</td>
<td><button>Edit</button></td>
</tr>
<tr>
<td>2</td>
<td>bob</td>
<td>bob_jon</td>
<td><button>Edit</button></td>
</tr>
</tbody>
</table>