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

i18next结合jQuery的插值函数失效问题求助

问题原因

页面上的<h1>是通过jquery-i18next的localize()方法渲染的,但你单独调用的i18next.t()仅生成了翻译字符串,并未将结果绑定到DOM元素上;同时localize()执行时未传入插值所需的userEmail参数,导致占位符无法被替换。

解决方法

有两种可行的修复方式:

方式一:在localize()调用时传入插值参数

修改rerender函数,为需要插值的元素单独传递参数:

const rerender = () => {
  // 给带占位符的标题传递插值参数
  $('h1[data-i18n="intro.title"]').localize({ userEmail: "email@email.com" });
  // 其他无需插值的元素正常渲染
  $('h3[data-i18n="intro.subTitle"]').localize();
}

方式二:通过DOM元素的data-options属性传递参数

直接在<h1>标签上添加data-options属性,以JSON格式传入插值参数:

<h1 data-i18n="intro.title" data-options='{"userEmail": "email@email.com"}'></h1>

这样原有的$('body').localize()就能自动读取参数并完成插值,无需修改rerender函数。

额外修正:语言切换的this指向问题

你的语言选择器change事件中,箭头函数的this不指向触发事件的元素,会导致无法正确获取选中语言。修改为以下代码:

$('#languageSwitcher').change(function() {
  const chosenLng = $(this).find("option:selected").attr('value');
  i18next.changeLanguage(chosenLng, () => {
    rerender();
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:25:21