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

WordPress音频插件自动添加括号,JS移除代码页面失效求助

移除WordPress音频插件自动添加的括号

问题场景

使用WordPress音频插件时,带有songwriter类的<span>标签会自动在文本前后添加括号,示例代码如下:

<span class="songwriter">(Female & Male dialog, Humorous, Storyteller, Cocky, Sassy)</span>

需要通过JavaScript移除这些多余的括号。

已尝试的代码

我编写了以下jQuery代码,在代码片段和JSFiddle测试时有效,但在实际页面中括号仍然存在:

JavaScript代码

$('span.songwriter').text(function(index, text) {
  return text.replace(/\(|\)/g, '');
});

测试用HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="songwriter">(Female & Male dialog, Humorous, Storyteller, Cocky, Sassy)</span>

解决思路及修正方案

出现这种差异的核心原因是实际页面中插件可能动态生成元素,或代码执行时机早于元素加载,以下是针对性的解决方法:

方法1:确保DOM完全加载后执行代码

将代码包裹在DOM就绪事件中,保证目标元素已生成后再执行处理逻辑,同时优化正则仅匹配首尾括号,避免误删文本内的括号:

$(document).ready(function() {
  $('span.songwriter').text(function(index, text) {
    return text.replace(/^\(|\)$/g, '');
  });
});

方法2:监听动态生成的元素

如果插件是异步加载生成songwriter元素,使用MutationObserver监听DOM变化,元素出现时自动处理:

const observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    const targetSpans = $(mutation.addedNodes).find('span.songwriter').addBack('span.songwriter');
    if (targetSpans.length > 0) {
      targetSpans.text(function(index, text) {
        return text.replace(/^\(|\)$/g, '');
      });
    }
  });
});

observer.observe(document.body, {
  childList: true,
  subtree: true
});

方法3:原生JavaScript实现(兼容无jQuery场景)

如果页面存在jQuery版本冲突或加载问题,用原生JS实现相同逻辑:

document.addEventListener('DOMContentLoaded', function() {
  const songwriterSpans = document.querySelectorAll('span.songwriter');
  songwriterSpans.forEach(function(span) {
    span.textContent = span.textContent.replace(/^\(|\)$/g, '');
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:42:53