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

如何在jQuery中获取唯一选择器并选中第二部分元素

如何选中页面中第二组相同选择器结构的元素

嘿,这个场景太常见啦~你现在的问题是因为$('.row table tr')会匹配页面里所有.row下的表格行,所以把前后两部分的内容都捞进来了。咱们只需要精准定位到第二个.row元素,再去获取它下面的表格内容就可以了,给你几个实用的方法:

方法1:使用jQuery的:eq()选择器(索引从0开始)

:eq(1)可以直接选中第二个.row(因为索引从0计数,第一个是eq(0)),然后再嵌套选择表格行:

const data = $('.row:eq(1) table tr').map(function() { 
  const a = $(this).find('td:first-child a'); 
  const td = $(this).find('td:last-child'); 
  return { 
    version: a.text(), 
    href: a.attr('href'), 
    date: td.text() 
  } 
}).get(); 
console.log(data)

方法2:使用.eq()方法(更推荐)

jQuery的.eq()方法比CSS选择器的兼容性和灵活性更好,尤其是在复杂DOM结构下:

const data = $('.row').eq(1).find('table tr').map(function() { 
  const a = $(this).find('td:first-child a'); 
  const td = $(this).find('td:last-child'); 
  return { 
    version: a.text(), 
    href: a.attr('href'), 
    date: td.text() 
  } 
}).get(); 
console.log(data)

方法3:使用CSS的nth-child()选择器(注意计数从1开始)

如果习惯用原生CSS选择器,可以用nth-child(2)选中第二个.row:

const data = $('.row:nth-child(2) table tr').map(function() { 
  const a = $(this).find('td:first-child a'); 
  const td = $(this).find('td:last-child'); 
  return { 
    version: a.text(), 
    href: a.attr('href'), 
    date: td.text() 
  } 
}).get(); 
console.log(data)

额外小技巧:通过兄弟关系定位

如果第二个.row是第一个的直接兄弟元素,还可以用兄弟选择器来定位,这样就算后续页面里前面加了其他元素,只要结构关系不变,依然能生效:

const data = $('.row').first().next().find('table tr').map(function() { 
  const a = $(this).find('td:first-child a'); 
  const td = $(this).find('td:last-child'); 
  return { 
    version: a.text(), 
    href: a.attr('href'), 
    date: td.text() 
  } 
}).get(); 
console.log(data)

这些方法最终都会只获取到你需要的第二部分表格里的那一行数据,完美解决你的问题~

内容的提问来源于stack exchange,提问作者Нек Траммм

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:28:34