在Web前端开发中,经常需要处理多级关联的表格数据,比如主表选中某行后,子表根据关联字段展示对应数据,同时支持在表格中查找指定内容并高亮,还能动态修改单元格的值。jQuery作为轻量级的JavaScript库,能很方便地实现这些交互需求。

基础表格结构搭建
首先我们需要搭建两级关联的表格结构,主表展示分类信息,子表展示分类下的明细数据,两者通过分类ID关联。
<table id="mainTable" border="1">
<thead>
<tr>
<th>分类ID</th>
<th>分类名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr data-id="1">
<td>1</td>
<td>电子产品</td>
<td><button class="showSub">查看明细</button></td>
</tr>
<tr data-id="2">
<td>2</td>
<td>办公用品</td>
<td><button class="showSub">查看明细</button></td>
</tr>
</tbody>
</table>
<table id="subTable" border="1" style="margin-top:20px;display:none;">
<thead>
<tr>
<th>明细ID</th>
<th>所属分类ID</th>
<th>商品名称</th>
<th>库存</th>
</tr>
</thead>
<tbody>
<tr data-cate-id="1">
<td>101</td>
<td>1</td>
<td>智能手机</td>
<td class="stock">50</td>
</tr>
<tr data-cate-id="1">
<td>102</td>
<td>1</td>
<td>平板电脑</td>
<td class="stock">30</td>
</tr>
<tr data-cate-id="2">
<td>201</td>
<td>2</td>
<td>打印纸</td>
<td class="stock">200</td>
</tr>
</tbody>
</table>
实现多级关联展示
点击主表的查看明细按钮,根据当前行的分类ID筛选子表中对应的数据行,实现两级表格的关联展示。
$(function(){
// 主表按钮点击事件
$('#mainTable').on('click', '.showSub', function(){
// 获取当前行的分类ID
var cateId = $(this).closest('tr').data('id');
// 隐藏所有子表行
$('#subTable tbody tr').hide();
// 展示匹配分类ID的子表行
$('#subTable tbody tr[data-cate-id="'+cateId+'"]').show();
// 显示子表
$('#subTable').show();
});
});
表格数据查找与高亮
添加查找输入框,输入关键词后遍历表格单元格,匹配的内容添加高亮样式,不匹配的内容移除高亮。
<input type="text" id="searchInput" placeholder="输入查找关键词">
<button id="searchBtn">查找</button>
<button id="resetBtn">重置</button>
<style>
.highlight{background-color:yellow;font-weight:bold;}
</style>
$(function(){
// 查找按钮点击事件
$('#searchBtn').click(function(){
var keyword = $('#searchInput').val().trim();
// 先移除所有高亮
$('#subTable tbody td').removeClass('highlight');
if(keyword){
// 遍历子表所有单元格
$('#subTable tbody td').each(function(){
var cellText = $(this).text();
// 判断是否包含关键词
if(cellText.indexOf(keyword) !== -1){
$(this).addClass('highlight');
}
});
}
});
// 重置按钮点击事件
$('#resetBtn').click(function(){
$('#searchInput').val('');
$('#subTable tbody td').removeClass('highlight');
});
});
动态值更新实现
支持双击子表的库存单元格,弹出输入框修改值,修改完成后更新单元格内容,同时可以添加简单的校验逻辑。
$(function(){
// 子表库存单元格双击事件
$('#subTable').on('dblclick', '.stock', function(){
var oldVal = $(this).text();
var input = $('<input type="number" value="'+oldVal+'" style="width:60px;">');
$(this).html(input);
input.focus();
// 输入框失去焦点时更新值
input.blur(function(){
var newVal = $(this).val();
// 校验输入是否为正整数
if(newVal && /^d+$/.test(newVal)){
$(this).parent().text(newVal);
}else{
alert('请输入有效的正整数库存值');
$(this).parent().text(oldVal);
}
});
// 回车键触发失去焦点
input.keyup(function(e){
if(e.keyCode === 13){
$(this).blur();
}
});
});
});
功能整合与注意事项
将上述功能整合后,需要注意以下几点:
- 事件绑定尽量使用
on方法委托,避免动态生成的子表行无法触发事件 - 查找高亮功能如果需要支持主表,只需把遍历的表格范围扩大到
#mainTable即可 - 动态更新值的时候,如果数据需要和后端同步,可以在值更新成功后发送Ajax请求保存数据
- 高亮样式可以根据需要调整,比如修改背景色或者文字颜色,提升可读性
以上实现方案覆盖了多级关联表格的核心交互需求,代码可以直接复制到本地运行测试,根据实际业务场景调整表格字段和逻辑即可。