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

jQuery实现仅包裹包含指定类的括号及内容

仅高亮内部包含.vbSup类的括号

问题描述

需要实现只给内部包含.vbSup类元素的括号(含括号本身)添加highlight高亮样式,但现有代码会错误高亮页面中所有括号,无法精准筛选目标括号。

原错误代码

var o = jQuery(".wp-site-blocks");
o.html(o.html().replace(/\([^\)]*?\)/g, '<span class="highlight">$&</span>'));

参考代码的缺陷

参考代码通过p:has(.vbSup)筛选包含目标类的段落,但会把段落内所有括号都高亮——哪怕括号里没有.vbSup(比如示例中第二个段落的括号,.vbSup在括号外部,却会被错误高亮)。

$o = $(".wp-site-blocks p:has(.vbSup)");
$o.html(function(i, oldhtml) {
  return oldhtml.replace(/\([^\)]*?\)/g, '<span class="highlight">$&</span>');
});

正确解决方案

方案1:精准正则匹配(适合简单结构)

直接匹配括号内包含.vbSup字符串的括号对,只替换这类目标括号:

var $container = jQuery(".wp-site-blocks");
$container.html(function(i, oldHtml) {
  // 匹配括号内包含.vbSup的完整括号对
  return oldHtml.replace(/\([^\)]*?vbSup[^\)]*?\)/g, '<span class="highlight">$&</span>');
});

方案2:DOM元素定位(更可靠)

通过DOM操作找到每个.vbSup元素,回溯定位它所在的括号对,再包裹高亮样式,避免正则处理HTML字符串的潜在误判:

jQuery(".vbSup").each(function() {
  var $sup = jQuery(this);
  var parentEl = $sup.parent();
  var parentHtml = parentEl.html();
  
  // 找到当前.vbSup所在括号的起始和结束位置
  var startPos = parentHtml.lastIndexOf('(', $sup[0].offsetLeft);
  var endPos = parentHtml.indexOf(')', $sup[0].offsetLeft);
  
  if (startPos !== -1 && endPos !== -1) {
    // 拼接新HTML,给目标括号包裹高亮类
    var newHtml = parentHtml.substring(0, startPos) +
                  '<span class="highlight">' +
                  parentHtml.substring(startPos, endPos + 1) +
                  '</span>' +
                  parentHtml.substring(endPos + 1);
    parentEl.html(newHtml);
  }
});

配套CSS样式

.highlight{
  background-color: yellow;
}

测试用HTML结构

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wp-site-blocks">
  <p>“Tragically, some 80% of the world’s hungry children live in countries with actual food surpluses, much of which is in the form of feed fed to animals which will be consumed by only the well-to-do consumers.”(Jeremy Rifkin, noted author of 23 books on the impact of global changes<span class="vbSup"><a href="#3af76716-b152-4705-a76f-f452228b13db" id="3af76716-b152-4705-a76f-f452228b13db-link">21</a></span>)</p>
  <p>“82% of the world’s starving children live in countries where food is fed to animals that are then killed and eaten by more well-off individuals in developed countries like the US, UK, and in Europe.” (Dr. Richard Oppenlander, 2012 Book )<span class="vbSup"><a href="#4bc2d108-83cb-49d4-918a-ea268c84b090" id="4bc2d108-83cb-49d4-918a-ea268c84b090-link">22</a></span></p>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:38:11