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

如何使用jQuery为句子中两个指定单词添加下划线 现有代码仅标注单个单词

问题根因

你的代码问题出在第二次替换时调用了$(this).text(),这个方法只会提取元素内的纯文本内容,会直接清空第一次替换时插入的<span>标签,导致第一个单词的下划线效果被覆盖丢失。

修改方案

把两次替换逻辑都放在原始纯文本上执行,全部替换完成后再统一赋值给元素的html属性即可,修改后的完整代码如下:

$(document).ready(function() {
  let firstword = 'web';
  let secondword = 'js';

  $(".field.ConditionsAccept>.caption:contains('" + secondword + "'):contains('" + firstword + "')").each(function() {
    // 提前获取原始纯文本
    const originText = $(this).text();
    const regex = new RegExp("(" + secondword + ")", 'g');
    const regex2 = new RegExp("(" + firstword + ")", 'g');
    // 完成两次替换后再统一赋值
    const resultHtml = originText
      .replace(regex, '<span class="word" style="text-decoration: underline">$1</span>')
      .replace(regex2, '<span class="word2" style="text-decoration: underline">$1</span>');
    $(this).html(resultHtml);
  });
});
.ConditionsAccept { width: 500px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="field ConditionsAccept">
  <caption class="caption">Here is some web and js stuff</caption>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:06:05