如何为表格每一行添加接受按钮?点击切换列仅首行生效其余行失效如何解决
问题根源
你在循环生成表格行时,给每行的两个操作列都设置了相同的id属性,而HTML规范要求同一个页面内的id必须唯一,document.getElementById()只会返回页面中第一个匹配对应id的元素,所以只有第一行的操作能生效。另外你第二列的标签还存在语法错误,style属性没有写闭合引号。
修复步骤
1. 修改PHP循环输出的HTML结构
把重复的id改为class,同时修复语法错误:
<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> <!-- id改为class --> <td class='refuseAccept' style='display:block;'> <button type='button' class='btn btn-outline-danger'>refuse</button> <button type='button' class='btn btn-outline-success m-2 acceptPpomentDoc' >accept</button> </td> <!-- id改为class,修复style属性漏写闭合引号的问题 --> <td class='showOptions m-2' style='display:none;' > <a href='#' title='view Details' class='text-success p-2 addappoment' > <i class='fas fa-calendar-check'></i></a> <a href='#' title='Edit' class='text-primary p-2 editBtn' ><i class='fas fa-user-edit'></i> </a> <a href='#' title='Delete' class='text-danger p2 deleteBtn' ><i class='fas fa-user-times'></i> </a> </td> </tr> "; } ?> </tbody>
2. 修改JavaScript逻辑
点击按钮时先定位到当前行,再筛选当前行内的操作列进行显示隐藏,不要全局查找元素:
$(document).on('click','.acceptPpomentDoc', function (){ // 获取当前点击按钮所在的行 const currentTr = $(this).closest('tr'); // 只操作当前行内的对应列 currentTr.find('.refuseAccept').hide(); currentTr.find('.showOptions').show(); });
额外说明
如果需要实现refuse按钮的相关逻辑,也可以用同样的方式,通过点击事件触发对象向上查找当前行,再操作行内元素,避免影响其他行的内容。
内容的提问来源于stack exchange,提问作者oliver
相关产品推荐
相关产品推荐

