如何实现动态表格每行评论按钮点击时显示对应评论输入框?
解决每行评论按钮独立触发输入框显示的问题
问题说明
需要实现点击表格每行的评论按钮时,在对应按钮下方显示独立的文本输入框,但当前所有按钮触发的事件无法区分对应行,导致无法正确显示目标输入框。
错误原因分析
- JS函数未传递行ID:原
myFunction()没有接收当前行的唯一ID参数,无法定位到对应行的输入框容器。 - PHP与JS执行时机冲突:JS代码中的
<?php $checks['id']?>在服务端执行时,只会保留循环最后一行的ID值,客户端无法动态获取每行的ID。 - CSS选择器错误:
#commentlinediv[<?php echo $checks['id']?>]是无效的ID选择器写法,无法正确隐藏输入框容器。
修正方案
1. 修改HTML代码(传递行ID并规范ID命名)
将按钮的onclick事件改为传递当前行的ID,同时将输入框容器的ID改为更规范的格式(避免括号可能引发的问题):
<div class="container-xxl flex-grow-1 container-p-y"> <h2 align="center"><?php echo $appname?></h2><br /> <div class="form-group"> <form name="add_name" id="add_name"> <div class="table-responsive"> <table class="table table-bordered" id="dynamic_field"> <?php while ($checks = mysqli_fetch_array($checksqry)) { $checkId = $checks['id']; echo '<tr>'; echo '<td style="width: 20%">'.$checks['check_name'].' <br><br> <input type="radio" class="btn-check" name="btn[' . $checkId . ']" id="btnpass[' . $checkId . ']" value="Pass"> <label class="btn rounded-pill btn-outline-success" for="btnpass[' . $checkId . ']">Pass</label>		 <input type="radio" class="btn-check" name="btn[' . $checkId . ']" id="btnwarning[' . $checkId . ']" value="Warning"> <label class="btn rounded-pill btn-outline-warning" for="btnwarning[' . $checkId . ']">Warning</label>		 <input type="radio" class="btn-check" name="btn[' . $checkId . ']" id="btnfail[' . $checkId . ']" value="Fail"> <label class="btn rounded-pill btn-outline-danger" for="btnfail[' . $checkId . ']">Fail</label>		 <button onclick="myFunction(' . $checkId . ')" type="button" name="comment[' . $checkId . ']" id="comment[' . $checkId . ']" class="btn btn-info" style="float: right"><img src="assets/comment.png" width="20px"></button> <br><br> <div id="commentlinediv-' . $checkId . '" class="commentlinediv"> <input type="text" class="text-line" placeholder="Type Comment Here" id="commentline-' . $checkId . '"/> </div> </td>'; echo '<tr>';}?> </table> <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" /> </div> </form> </div> </div>
2. 修改CSS代码(正确隐藏输入框容器)
使用类选择器统一隐藏所有输入框容器,比ID选择器更简洁:
input[type="text"] { border:none; /* 移除浏览器默认样式 */ border-bottom:1px solid black; /* 添加自定义下划线 */ } .text-line { background-color: transparent; color: black; outline: none; outline-style: none; border-top: none; border-left: none; border-right: none; border-bottom: solid #eeeeee 1px; padding: 3px 10px; width: 300px; } .commentlinediv { display: none; }
3. 修改JS函数(接收ID并定位对应容器)
让函数接收行ID参数,根据ID找到对应的输入框容器并切换显示状态:
function myFunction(checkId) { // 拼接目标容器的ID const divId = 'commentlinediv-' + checkId; const commentDiv = document.getElementById(divId); // 切换显示/隐藏状态,也可以直接设置为"block"或"inline" commentDiv.style.display = commentDiv.style.display === 'none' ? 'block' : 'none'; }
补充说明
- 规范ID命名:避免使用
[]这类特殊字符作为ID的一部分,改用-连接符,减少DOM选择时的潜在问题。 - 切换逻辑:使用切换显示状态的方式可以让按钮实现点击显示、再次点击隐藏的交互,比单纯设置固定显示值更友好。
内容的提问来源于stack exchange,提问作者Datapoynt Systems
相关产品推荐
相关产品推荐

