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

多语言网站翻译后内嵌链接消失的技术解决方案咨询

解决语言切换时保留HTML链接的问题

我正在开发一款支持语言切换的网站,已将部分词汇设置为跳转至说明页面的链接,但使用textContent实现翻译时,段落中的<a>链接会被转为纯文本而消失。相关代码如下:

HTML代码

<h4 class="critTitle">Critical infrastructure security</h4>
<p class="crit">Critical infrastructure security addresses the protection of computer systems, applications, networks, data and digital assets that are critical to a society's national security, economic health and public safety. In the United States, the <a href="https://www.nist.gov/">National Institute of Standards and Technology</a> (NIST) has developed a cybersecurity framework to support IT vendors in this area. In addition, the U.S. Department of Homeland Security's Cybersecurity and Infrastructure Security Agency (CISA) provides additional guidance to strengthen the security of critical infrastructures.</p>

<div class="language">
  <div class="langWrap">
    <a href="#"  language='english' class="lang active">EN</a>
    <a href="#"  language='spanish' class="lang">ES</a>
  </div>
</div>

当前JavaScript代码

const langEl = [...document.querySelectorAll(".lang")];
const critTitleEl = document.querySelector(".critTitle");
const critEl = document.querySelector(".crit");

langEl.forEach((el) => {
    el.addEventListener("click", () => {
      langEl.map(item => item.classList.contains("active") ? item.classList.remove("active") : false);
      el.classList.add("active");
      chosenLanguage = el.innerText;
      search();
  
      const attr = el.getAttribute("language");

      critTitleEl.textContent = data[attr].critTitle;
      critEl.textContent = data[attr].crit;
 });

var data = {
english: {
      critTitle: "Critical infrastructure security",
      crit: "Critical infrastructure security addresses the protection of computer systems, applications, networks, data and digital assets that are critical to a society's national security, economic health and public safety. In the United States, the National Institute of Standards and Technology (NIST) has developed a cybersecurity framework to support IT vendors in this area. In addition, the U.S. Department of Homeland Security's Cybersecurity and Infrastructure Security Agency (CISA) provides additional guidance to strengthen the security of critical infrastructures."
},
spanish: {
      critTitle: "Seguridad de las infraestructuras críticas",
      crit: "La seguridad de las infraestructuras críticas se centra en la protección de sistemas informáticos, aplicaciones, redes, datos y activos digitales que son fundamentales para la seguridad nacional, la salud económica y la seguridad pública de una sociedad. En Estados Unidos, el Instituto Nacional de Normas y Tecnología (NIST) ha desarrollado un marco de ciberseguridad para apoyar a los proveedores de TI en este ámbito. Además, la Agencia de Ciberseguridad y Seguridad de las Infraestructuras (CISA) del Departamento de Seguridad Nacional de EE.UU. ofrece orientaciones adicionales para reforzar la seguridad de las infraestructuras críticas."
}

解决方案

方法1:拆分文本与链接元素(推荐,安全可控)

将段落中的静态文本和链接文本拆分,单独包裹元素,翻译时仅修改对应文本内容,保留原有DOM结构。

步骤1:修改HTML结构

给静态文本块和链接文本分别添加类名,便于单独控制:

<p class="crit">
  <span class="crit-part1">Critical infrastructure security addresses the protection of computer systems, applications, networks, data and digital assets that are critical to a society's national security, economic health and public safety. In the United States, the </span>
  <a href="https://www.nist.gov/"><span class="link-nist">National Institute of Standards and Technology</span></a>
  <span class="crit-part2"> (NIST) has developed a cybersecurity framework to support IT vendors in this area. In addition, the U.S. Department of Homeland Security's </span>
  <span class="link-cisa">Cybersecurity and Infrastructure Security Agency</span>
  <span class="crit-part3"> (CISA) provides additional guidance to strengthen the security of critical infrastructures.</span>
</p>

步骤2:调整翻译数据结构

把翻译内容拆分成对应文本块:

var data = {
  english: {
    critTitle: "Critical infrastructure security",
    critPart1: "Critical infrastructure security addresses the protection of computer systems, applications, networks, data and digital assets that are critical to a society's national security, economic health and public safety. In the United States, the ",
    nistLinkText: "National Institute of Standards and Technology",
    critPart2: " (NIST) has developed a cybersecurity framework to support IT vendors in this area. In addition, the U.S. Department of Homeland Security's ",
    cisaLinkText: "Cybersecurity and Infrastructure Security Agency",
    critPart3: " (CISA) provides additional guidance to strengthen the security of critical infrastructures."
  },
  spanish: {
    critTitle: "Seguridad de las infraestructuras críticas",
    critPart1: "La seguridad de las infraestructuras críticas se centra en la protección de sistemas informáticos, aplicaciones, redes, datos y activos digitales que son fundamentales para la seguridad nacional, la salud económica y la seguridad pública de una sociedad. En Estados Unidos, el ",
    nistLinkText: "Instituto Nacional de Normas y Tecnología",
    critPart2: " (NIST) ha desarrollado un marco de ciberseguridad para apoyar a los proveedores de TI en este ámbito. Además, la ",
    cisaLinkText: "Agencia de Ciberseguridad y Seguridad de las Infraestructuras",
    critPart3: " (CISA) del Departamento de Seguridad Nacional de EE.UU. ofrece orientaciones adicionales para reforzar la seguridad de las infraestructuras críticas."
  }
};

步骤3:修改JavaScript逻辑

获取所有拆分后的元素,分别设置翻译内容:

const langEl = [...document.querySelectorAll(".lang")];
const critTitleEl = document.querySelector(".critTitle");
// 获取拆分后的文本元素
const critPart1 = document.querySelector(".crit-part1");
const nistLinkText = document.querySelector(".link-nist");
const critPart2 = document.querySelector(".crit-part2");
const cisaLinkText = document.querySelector(".link-cisa");
const critPart3 = document.querySelector(".crit-part3");

langEl.forEach((el) => {
    el.addEventListener("click", () => {
      // 切换激活状态
      langEl.forEach(item => item.classList.remove("active"));
      el.classList.add("active");
      
      const attr = el.getAttribute("language");
      const langData = data[attr];

      // 逐个设置翻译内容
      critTitleEl.textContent = langData.critTitle;
      critPart1.textContent = langData.critPart1;
      nistLinkText.textContent = langData.nistLinkText;
      critPart2.textContent = langData.critPart2;
      cisaLinkText.textContent = langData.cisaLinkText;
      critPart3.textContent = langData.critPart3;
    });
});

方法2:使用innerHTML直接插入带链接的HTML

如果翻译内容由自己维护(无安全风险),可以直接在翻译数据中写入带<a>标签的HTML,用innerHTML替换内容:

步骤1:调整翻译数据结构

var data = {
  english: {
    critTitle: "Critical infrastructure security",
    crit: "Critical infrastructure security addresses the protection of computer systems, applications, networks, data and digital assets that are critical to a society's national security, economic health and public safety. In the United States, the <a href='https://www.nist.gov/'>National Institute of Standards and Technology</a> (NIST) has developed a cybersecurity framework to support IT vendors in this area. In addition, the U.S. Department of Homeland Security's Cybersecurity and Infrastructure Security Agency (CISA) provides additional guidance to strengthen the security of critical infrastructures."
  },
  spanish: {
    critTitle: "Seguridad de las infraestructuras críticas",
    crit: "La seguridad de las infraestructuras críticas se centra en la protección de sistemas informáticos, aplicaciones, redes, datos y activos digitales que son fundamentales para la seguridad nacional, la salud económica y la seguridad pública de una sociedad. En Estados Unidos, el <a href='https://www.nist.gov/'>Instituto Nacional de Normas y Tecnología</a> (NIST) ha desarrollado un marco de ciberseguridad para apoyar a los proveedores de TI en este ámbito. Además, la Agencia de Ciberseguridad y Seguridad de las Infraestructuras (CISA) del Departamento de Seguridad Nacional de EE.UU. ofrece orientaciones adicionales para reforzar la seguridad de las infraestructuras críticas."
  }
};

步骤2:修改JavaScript逻辑

将textContent替换为innerHTML:

const langEl = [...document.querySelectorAll(".lang")];
const critTitleEl = document.querySelector(".critTitle");
const critEl = document.querySelector(".crit");

langEl.forEach((el) => {
    el.addEventListener("click", () => {
      langEl.forEach(item => item.classList.remove("active"));
      el.classList.add("active");
      
      const attr = el.getAttribute("language");
      const langData = data[attr];

      critTitleEl.textContent = langData.critTitle;
      // 使用innerHTML插入带链接的HTML
      critEl.innerHTML = langData.crit;
    });
});

注意:此方法存在XSS风险,仅适用于翻译内容完全可控的场景,避免使用用户提交的内容作为翻译源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:48:16