jQuery函数失效:无法高亮表格连续值及跨表格查询填充问题
表格高亮与下一级数值自动填充解决方案
需求说明
- 在ID为
cb的「BASIC」输入框中输入表格单元格数值(例如65000)时:- 匹配数值所在行添加
highlight类(红色高亮样式) - 匹配行的紧邻下一行添加
highlight2类(蓝色高亮样式)
- 匹配数值所在行添加
- 从ID为
le11的表格中,找到大于输入值的最小数值(例如67700),并自动填充到ID为nb的「Next Basic」输入框中
原代码问题
原jQuery函数逻辑混乱,无法实现上述需求:
- 遍历所有表格单元格时重复添加/移除样式,导致样式异常
- 未实现从
le11表格筛选目标数值并填充的逻辑 - DOM选择器使用错误(如
closest('tr')冗余,跨表格选择逻辑无效)
修正后的完整代码
JavaScript
$(function() { $('#cb').on('change keyup', function() { const inputVal = $(this).val().trim(); const numVal = parseInt(inputVal, 10); // 清空所有高亮样式,避免残留 $('#le10 tr').removeClass('highlight highlight2'); if (!isNaN(numVal)) { // 处理le10表格的高亮逻辑 const matchedTr = $('#le10 td').filter(function() { return parseInt($(this).text().trim(), 10) === numVal; }).parent('tr'); if (matchedTr.length) { matchedTr.addClass('highlight'); matchedTr.next('tr').addClass('highlight2'); } // 处理le11表格的数值筛选与填充 const le11Numbers = $('#le11 td').map(function() { return parseInt($(this).text().trim(), 10); }).get().filter(n => !isNaN(n) && n > numVal); if (le11Numbers.length) { const closestNext = Math.min(...le11Numbers); $('#nb').val(closestNext); } else { $('#nb').val(''); } } else { // 输入非数字时清空样式和填充框 $('#nb').val(''); } }); });
CSS
.highlight { color: red; background-color: yellow; font-weight: bold; } .highlight2 { color: blue; background-color: greenyellow; font-weight: bold; }
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div class="container"> <div class="row"> <div class="col-md-6"> <table width="100%" border="0"> <tr> <td>Basic</td> <td><input class="form-control" type="text" name="cb" id="cb" autocomplete="off" /></td> </tr> </table> </div> </div> </div> <table class="table table-responsive"> <tr> <td> <h6>Current Level</h6> </td> <td> <h6>Next Level</h6> </td> <td> <h6>Next Basic</h6> </td> </tr> <tr> <td> <table id="le10" class="table table-responsive table-striped"> <tr> <td>56100</td> </tr> <tr> <td>57800</td> </tr> <tr> <td>59500</td> </tr> <tr> <td>61300</td> </tr> <tr> <td>63100</td> </tr> <tr> <td>65000</td> </tr> <tr> <td>67000</td> </tr> </table> </td> <td> <table id="le11" class="table table-responsive table-striped"> <tr> <td>67700</td> </tr> <tr> <td>69700</td> </tr> <tr> <td>71800</td> </tr> <tr> <td>74000</td> </tr> </table> </td> <td> Next Basic<input class="form-control" type="text" name="nb" id="nb" /> </td> </tr> </table>
关键改进点
- 先清空所有高亮样式,避免多次输入后样式残留
- 使用数值类型比较,避免字符串匹配的误差
- 分离
le10高亮逻辑与le11数值筛选逻辑,代码更清晰 - 处理输入非数字的边界情况,自动清空填充框
内容的提问来源于stack exchange,提问作者shankar_sb
相关产品推荐
相关产品推荐

