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

如何用jQuery批量为动态生成的机构名称包裹<a>标签

通用批量为机构名称添加链接的jQuery方案

需求背景

现有页面结构示例:

<div class="vc_acf organisation">
    <span class="vc_acf-label">Organisation:</span> CLEMI
</div>

希望将其修改为:

<div class="vc_acf organisation">
    <span class="vc_acf-label">Organisation:</span> <a href="https://beglobal.toc-web.site/resources/clemi">CLEMI</a>
</div>

目前已实现单个机构的替换代码,但页面中存在大量动态生成的.organisation元素,部分机构名称为多词形式(如“SOS Faim”),不想逐个编写替换规则,需要一套通用方法:自动选中元素内的机构名称,为其包裹<a>标签,并将名称转为小写、空格替换为横杠的格式作为URL路径部分。

通用解决方案

以下是实现该需求的jQuery代码:

(function($) {
    $(".organisation").each(function() {
        const html = $(this).html();
        // 匹配标签后的机构名称,兼容多词内容
        const updatedHtml = html.replace(/(<span class="vc_acf-label">Organisation:<\/span>)\s*([\w\s]+)/, function(match, labelText, orgName) {
            const trimmedName = orgName.trim();
            // 处理名称为URL路径格式
            const urlPath = trimmedName.toLowerCase().replace(/\s+/g, '-');
            // 拼接带链接的结构
            return `${labelText} <a href="https://beglobal.toc-web.site/resources/${urlPath}">${trimmedName}</a>`;
        });
        $(this).html(updatedHtml);
    });
})(jQuery);

代码说明

  • 通过正则精准匹配标签与机构名称的结构,确保只抓取标签后的机构文本,避免误替换其他内容
  • 对机构名称的处理逻辑:去除首尾空格→转换为全小写→将所有空格替换为横杠,生成符合要求的URL路径
  • 动态生成带链接的HTML结构,批量替换所有.organisation元素的内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:22:17