动态表格下拉框切换时无法在对应行显示输入框的修复咨询
问题解决:下拉框切换时仅显示当前行的对应输入框
我明白你遇到的麻烦了——现在你的代码会操作页面上所有带.schedule、.custom类的元素,所以切换下拉框时输入框会乱跳到其他行。核心问题是没有限定操作范围,全局选择器影响了所有行,下面是具体的修正方案:
问题根源
你的原代码里用了jQuery('.schedule')这类全局选择器,会选中页面上所有匹配的元素,而不是当前下拉框所在行的元素。另外用remove()会直接把DOM元素删掉,导致后续切换选项时没法再恢复这些元素。
修正后的完整代码
1. HTML部分(仅需添加初始隐藏样式)
<style> /* 让三个输入框区域默认隐藏 */ .schedule, .custom, .submit_value { display: none; margin-top: 8px; /* 可选,优化视觉间距 */ } </style> <table class="table table-bordred table-striped"> <thead> <th>NAME</th> <th>STATUS</th> </thead> <tbody> <?php foreach($student as $per_student): ?> <tr> <td><?php echo $per_student->name; ?></td> <td> <select class="can-dd" onchange="myFunction(this)" name="status"> <option value="">STATUS</option> <option value="Accepted">Accepted</option> <!-- 去掉原选项里的多余空格 --> <option value="Forwarded">Forwarded</option> <option value="Schedule">Schedule</option> <option value="Custom">Custom</option> </select> <div class="schedule"> <input type="text" placeholder="schedule" name="schedule"> <button type="submit" class="btn btn-primary ">SUBMIT</button> </div> <div class="custom"> <input type="text" placeholder="custom" name="custom"> <button type="submit" class="btn btn-primary ">SUBMIT</button> </div> <div class="submit_value"> <button type="submit" class="btn btn-primary ">SUBMIT</button> </div> </td> </tr> <?php endforeach; ?> </tbody> </table>
2. JavaScript部分(关键修改:限定操作范围)
<script type="text/javascript"> function myFunction(selectObject) { var value = selectObject.value.trim(); // 去除选项值的首尾空格,避免匹配错误 // 定位到当前下拉框所在的<td>元素,限定操作范围为当前行 var $currentTd = jQuery(selectObject).parent(); // 先隐藏当前行内所有相关的输入框区域 $currentTd.find(".schedule, .custom, .submit_value").hide(); // 根据选中值显示对应的区域 if(value === 'Schedule'){ $currentTd.find(".schedule").show(); } else if(value === 'Custom'){ $currentTd.find(".custom").show(); } else { $currentTd.find(".submit_value").show(); } } </script>
核心修改点说明
- 限定操作范围:通过
jQuery(selectObject).parent()获取当前下拉框所在的<td>,再用find()只在这个范围内查找元素,确保只操作当前行的内容。 - 替换remove()为hide()/show():
remove()会永久删除DOM元素,而hide()只是隐藏,后续切换选项时可以重新显示,避免元素丢失。 - 清理选项值空格:原选项中部分值带有多余空格(比如
"Accepted "),用trim()去除后避免匹配失败。
这样修改后,切换下拉框时就只会在当前行显示对应的输入框了!
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

