You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery为匹配的首个和最后一个tbody元素添加类名

嘿,这事儿简单得很,用jQuery的几个基础选择器就能搞定,给你两种靠谱的实现方式,按需选就行:

基础实现(选中表格下所有tbody的第一个和最后一个)

如果只是要给.section-table表格里的第一个tbody和最后一个tbody添加类名,直接用:first和:last选择器就行,或者用.first()、.last()方法,代码如下:

方式1:直接用选择器

// 给第一个tbody添加自定义类名,比如first-tbody
$('.section-table tbody:first').addClass('first-tbody');
// 给最后一个tbody添加自定义类名,比如last-tbody
$('.section-table tbody:last').addClass('last-tbody');

方式2:链式调用方法

这种方式更连贯,适合需要对tbody集合做多个操作的场景:

$('.section-table tbody')
  .first().addClass('first-tbody').end() // 选中第一个tbody加类,然后回到tbody集合
  .last().addClass('last-tbody'); // 选中最后一个tbody加类

进阶:排除已有特定类的tbody

如果你的需求是跳过已经有found类的tbody,只给没有这个类的第一个和最后一个加类,那只需要调整选择器,加上:not(.found)过滤:

// 无found类的第一个tbody
$('.section-table tbody:not(.found):first').addClass('first-tbody');
// 无found类的最后一个tbody
$('.section-table tbody:not(.found):last').addClass('last-tbody');

注意事项

  • 把代码里的first-tbody和last-tbody替换成你实际需要的类名即可。
  • 确保代码在DOM加载完成后执行,要么包裹在$(document).ready()里,要么放在页面底部(</body>标签之前):
$(document).ready(function() {
  // 这里放上面的代码
  $('.section-table tbody:first').addClass('first-tbody');
  $('.section-table tbody:last').addClass('last-tbody');
});

内容的提问来源于stack exchange,提问作者NewUser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:47:46