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

使用jQuery判断相邻元素含指定文本并获取对应表格值

解决方法:定位到Brand C对应的价格

先把你的表格结构转成更清晰的格式:

产品品牌价格
AppleBrand A1000
AppleBrand B2000
AppleBrand C3000
AppleBrand D4000

你原来的代码之所以输出1000,是因为$("td:contains('Apple')").first()只会选中第一个包含Apple的<td>,接着取它后面第二个<td>的内容,自然就是第一行的价格了。

要精准拿到Brand C对应的3000,这里有几种靠谱的方法:

方法1:直接定位Brand C的td(简单直接)

如果页面里只有这一处的Brand C,直接选中它然后取相邻的价格td就行:

const targetPrice = $("td:contains('Brand C')").next().text();
console.log(targetPrice); // 输出3000

方法2:关联Apple和Brand C(更严谨)

如果页面里可能有其他Brand C的条目,需要确保是Apple那一行的,可以用过滤的方式:

// 找到所有包含Apple的td,过滤出下一个td是Brand C的,再取价格
const targetPrice = $("td:contains('Apple')").filter(function() {
  return $(this).next().text() === 'Brand C';
}).next().next().text();
console.log(targetPrice); // 输出3000

方法3:用行选择器精准匹配(语义化更强)

直接定位到第一个td是Apple,第二个td是Brand C的行,然后取第三个td的内容:

const targetPrice = $("tr").filter(function() {
  const tds = $(this).find("td");
  return tds.eq(0).text() === 'Apple' && tds.eq(1).text() === 'Brand C';
}).find("td").eq(2).text();
console.log(targetPrice); // 输出3000

或者用更简洁的链式选择器写法:

const targetPrice = $("tr:has(>td:first-child:contains('Apple')):has(>td:nth-child(2):contains('Brand C')) td:nth-child(3)").text();
console.log(targetPrice); // 输出3000

这几种方法都能帮你拿到想要的3000,根据你的页面复杂度选合适的就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:43:45