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

如何用jQuery获取内层标签中带active类的span文本?

jQuery获取带active类的span文本问题解决

问题场景

HTML结构示例(实际位于表格中):

<div class="strategiesddata">
<div class="strattabletodivmobright">
<p class="stategybuysellchkbox clearfix">
<span class="BUY active" name="spbuy">B</span>
<span class="SELL " name="spsell">S</span>
</p></div>

<div class="strattabletodivmobright">
<p class="stategybuysellchkbox clearfix">
<span class="BUY " name="spbuy">B</span>
<span class="SELL active" name="spsell">S</span>
</p></div>
</div>

需求:获取每个.stategybuysellchkbox容器中带active类的span文本(第一个取B,第二个取S)。

原代码错误分析

第一段代码错误

$(".strategiesddata").each(function () {
 t = $(this);
var tst = t.find(".stategybuysellchkbox").closest(".active").html();
});
  • closest(".active")是向上查找父级元素,但.active是.stategybuysellchkbox内部的子元素,无法通过向上查找获取,返回空jQuery对象,调用.html()自然得到undefined。

第二段代码错误

$(".strategiesddata").each(function () {
 t = $(this);
var tst = t.closest(".stategybuysellchkbox").find("span[.active]").html();
});
  1. t.closest(".stategybuysellchkbox"):closest()从当前元素(.strategiesddata)向上查找父级,但.stategybuysellchkbox是它的后代元素,无法找到;
  2. span[.active]是错误的选择器语法,类选择器应写为span.active,而非属性选择器格式。

正确实现方法

方法一:直接遍历目标容器

遍历每个.stategybuysellchkbox,查找内部的.active span并获取文本:

$(".strategiesddata .stategybuysellchkbox").each(function() {
  // 用text()获取纯文本,比html()更适合当前场景
  var activeText = $(this).find(".active").text();
  console.log(activeText); // 依次输出B、S
});

方法二:从根容器开始遍历

如果需要从.strategiesddata层级开始处理:

$(".strategiesddata").each(function() {
  var $root = $(this);
  // 查找当前根容器下所有符合条件的span
  $root.find(".stategybuysellchkbox .active").each(function() {
    var activeText = $(this).text();
    console.log(activeText);
  });
});

说明:使用.find()向下查找后代元素是正确的方向,.text()专门用于获取元素的纯文本内容,比.html()更适配当前仅需文本的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:45:15