使用jQuery多次修改HTML内容失效:按钮点击切换仅生效一次
问题根因
- 容器ID匹配错误:点击Enroll按钮时,代码中指定的Drop按钮写入目标
#xxxToDropBtn、状态更新目标#xxxToEnrolledString在渲染的页面中不存在,实际对应的容器应为#xxxToEmpty(存放Drop按钮)、#xxxToEnrollButton(存放选课状态/Enroll按钮) - 切换逻辑不完整:点击Enroll按钮生成Drop按钮后,没有同步清空Enroll按钮所在的容器,也没有回写选课状态文本
修复代码
调整后jQuery代码
合并冗余的ready事件,修正容器ID匹配逻辑:
$(document).ready(function() { // 退选按钮点击逻辑 $(document).on('click','.dropJQ',function () { const classIdValue = this.value; const $statusContainer = $(`#${classIdValue}ToEnrollButton`); const $btnContainer = $(`#${classIdValue}ToEmpty`); $.get("rmov.php", {classID : classIdValue}, function(response){ // 变量拼写与后端返回值匹配即可,原拼写错误opeartion可改为operation if(response === "success"){ alert("退选操作失败"); }else{ alert("退选操作成功!"); } // 状态位替换为选课按钮 $statusContainer.html(`<button class='enrollJQ' value='${classIdValue}'>Enroll</button>`); // 清空退选按钮容器 $btnContainer.empty(); }); }); // 选课按钮点击逻辑 $(document).on('click','.enrollJQ',function () { const classIdValue = this.value; const $statusContainer = $(`#${classIdValue}ToEnrollButton`); const $btnContainer = $(`#${classIdValue}ToEmpty`); $.get("rsv.php", {classID : classIdValue}, function(response){ if(response === "success"){ alert("选课操作失败"); }else{ alert("选课操作成功!"); } // 回写已选状态 $statusContainer.text("Enrolled"); // 生成退选按钮 $btnContainer.html(`<button class='dropJQ' value='${classIdValue}'>Drop</button>`); }); }); });
PHP渲染优化(可选)
原循环输出的tr ID重复,可调整为动态ID避免后续DOM操作冲突:
while($row= mysqli_fetch_assoc($result)) { echo '<tr id="trenrolld_'.$row['id'].'">'; echo '<td><a href="InformationPage.php?classID='.$row['id'].'">'.$row['name'].'</a> </td>'; echo '<td id="'.$row['id'].'ToEnrollButton">Enrolled</td>'; echo '<td id="'.$row['id'].'ToEmpty"><button class="dropJQ" value="'.$row['id'].'" >Drop</button></td>'; echo '</tr>'; }
内容的提问来源于stack exchange,提问作者Amani
相关产品推荐
相关产品推荐

