
本文旨在解决在动态生成的html表格中,为每一行添加一个“接受”按钮,并实现点击该按钮后显示特定列,隐藏其他列的功能。重点在于避免使用重复id,并利用jquery选择器精准控制每一行元素的显示与隐藏,确保表格交互的正确性与可维护性。
在Web开发中,经常会遇到需要动态生成表格,并且为每一行添加交互功能的需求。一个常见的场景是,表格中包含一个“接受”按钮,点击该按钮后,需要显示该行的一些操作选项,同时隐藏一些初始状态下的元素。本文将详细介绍如何使用HTML、PHP和JavaScript(jQuery)来实现这一功能,并着重强调避免使用重复ID,以及如何使用jQuery选择器来正确操作DOM元素。
原始代码中存在一个关键问题:在循环中使用了相同的ID(refuseAccept和showOptions)多次,这违反了HTML规范,导致JavaScript代码只能操作第一个匹配该ID的元素,从而使得只有表格的第一行“接受”按钮有效。
为了解决这个问题,我们需要:
以下是修改后的代码示例:
HTML/PHP (表格生成部分)
<tbody>
<?php
$sql = "SELECT * FROM appointments INNER JOIN patients ON appointments.patientID =patients.patientID WHERE docID='$doctorId'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$i=0;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$i++;
extract($row);
echo"<tr>
<td >$i</td>
<td>{$patientFName} {$patientLName}</td>
<td>{$AppStart}</td>
<td>{$AppEnd}</td>
<td class='refuseAccept'>
<button type='button' class='btn btn-outline-danger'>拒绝</button>
<button type='button' class='btn btn-outline-success m-2 acceptPpomentDoc'>接受</button>
</td>
<td class='showOptions m-2' style='display:none;'>
<a href='#' title='查看详情' class='text-success p-2 addappoment'> <i class='fas fa-calendar-check'></i></a>
<a href='#' title='编辑' class='text-primary p-2 editBtn'><i class='fas fa-user-edit'></i> </a>
<a href='#' title='删除' class='text-danger p2 deleteBtn'><i class='fas fa-user-times'></i> </a>
</td>
</tr>";
}
?>
</tbody>JavaScript (jQuery)
$(document).on('click', '.acceptPpomentDoc', function() {
// $(this) references the item clicked, in this case the accept button
$(this).closest('tr').find('.showOptions').show();
// find the containing <tr>, then from there find the div with class name showOptions and set display:block
$(this).closest('tr').find('.refuseAccept').hide();
// find the containing <tr>, then from there find the div with class name refuseAccept and set display:none
});CSS (可选,用于初始隐藏.showOptions)
.showOptions {
display: none;
}通过避免使用重复ID,并结合jQuery选择器,我们可以轻松地为动态生成的表格添加交互功能。本文提供了一个清晰的示例,展示了如何为表格的每一行添加一个“接受”按钮,并实现点击该按钮后显示特定列,隐藏其他列的功能。 这种方法不仅解决了原始代码中的问题,还提高了代码的可维护性和可扩展性。
以上就是如何为表格的每一行创建一个接受按钮?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号