如何用jQuery高亮HTML表格中输入值对应单元格及紧邻下一个单元格
解决方案
要实现输入值匹配后高亮当前单元格及紧邻下一个单元格的功能,只需修改原有的JavaScript逻辑,在找到匹配项时同时处理下一个单元格即可。以下是修改后的完整代码:
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap.css"> <style> .highlight { color: red; background-color: yellow; font-weight: bold; } </style> </head> <body> <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> </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> <tr><td>69000</td></tr> <tr><td>71100</td></tr> <tr><td>73200</td></tr> <tr><td>75400</td></tr> <tr><td>77700</td></tr> </table> </td> </tr> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ $('#cb').on('input', function() { var textboxValue = $(this).val().trim().toUpperCase(); // 先清除所有高亮状态,避免残留 $('#le10 td').removeClass('highlight'); if(textboxValue.length > 0) { $('#le10 td').each(function() { var cellText = $(this).text().toUpperCase(); if (cellText.indexOf(textboxValue) > -1) { $(this).addClass('highlight'); // 获取当前单元格所在行的下一行,为其中的单元格添加高亮 var nextRow = $(this).closest('tr').next('tr'); if(nextRow.length > 0) { nextRow.find('td').addClass('highlight'); } } }); } }); }); </script> </body> </html>
关键修改说明:
- 每次输入触发时,先统一清除所有单元格的高亮类,避免之前的高亮状态残留。
- 找到匹配的单元格后,通过
closest('tr').next('tr')定位到当前行的下一行,判断该行存在后,为其中的单元格添加高亮样式。 - 优化了输入值的获取逻辑,直接使用
$(this)获取当前输入框,减少重复的DOM查询操作。
这样就能实现需求:输入框输入数值时,匹配的单元格会被高亮,同时紧邻它的下一个单元格也会同步高亮;清空输入框时,所有高亮状态自动消失。
内容的提问来源于stack exchange,提问作者shankar_sb
相关产品推荐
相关产品推荐

