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

i18Next.js实现input占位符及自定义属性翻译失败求助

解决i18Next.js中 placeholder及属性翻译无效问题

你当前使用纯i18Next.js(23.4.4版本)实现网站国际化时,普通元素(如<p>)的翻译功能正常,但<input>的placeholder这类属性,用[placeholder]MYKEY格式的data-i18n属性无法生效,目前卡在此环节。

现有代码

初始化脚本

<script src="/i18next/i18next.js"></script>
<script src="/i18next/i18nextHttpBackend.js"></script>
<script src="/i18next/i18nextBrowserLanguageDetector.js"></script>

<script>
  i18next
    .use(i18nextHttpBackend)
    .use(i18nextBrowserLanguageDetector)
    .init(
        {
            fallbackLng: 'en',
            backend: {
                loadPath: 'https://www.example.com/localization/{{lng}}_json',
            }
        }
    )
    .then(() => {
        document.body.querySelectorAll('[data-i18n]').forEach(element => {
            element.innerHTML = i18next.t(element.getAttribute('data-i18n'));
        });
    });
</script>

翻译JSON文件

{
    "contact": {
        "CONTACT_FORM_NAME_LABEL": "NAME",
        "CONTACT_FORM_NAME_PLACEHOLDER": "Enter your name"
    }
}

Input HTML代码

<input type="text" data-i18n="[placeholder]contact.CONTACT_FORM_NAME_PLACEHOLDER">

问题原因

你自行编写的遍历逻辑只处理了元素的innerHTML,但[placeholder]KEY是i18Next的属性翻译语法,现有代码没有解析该格式,无法为input设置placeholder属性。

修复方案

修改初始化后的遍历逻辑,解析data-i18n属性中的语法,区分内容翻译和属性翻译:

修改后的初始化脚本

<script src="/i18next/i18next.js"></script>
<script src="/i18next/i18nextHttpBackend.js"></script>
<script src="/i18next/i18nextBrowserLanguageDetector.js"></script>

<script>
  i18next
    .use(i18nextHttpBackend)
    .use(i18nextBrowserLanguageDetector)
    .init({
        fallbackLng: 'en',
        backend: {
            loadPath: 'https://www.example.com/localization/{{lng}}_json',
        }
    })
    .then(() => {
        document.body.querySelectorAll('[data-i18n]').forEach(element => {
            const i18nAttr = element.getAttribute('data-i18n');
            // 解析属性翻译格式:[attr]key
            const attrMatch = i18nAttr.match(/^\[([a-zA-Z0-9-]+)\](.+)$/);
            if (attrMatch) {
                // 处理属性翻译
                const attrName = attrMatch[1];
                const translationKey = attrMatch[2].trim();
                element.setAttribute(attrName, i18next.t(translationKey));
            } else {
                // 处理普通内容翻译
                element.innerHTML = i18next.t(i18nAttr);
            }
        });
    });
</script>

逻辑说明

  • 新增正则匹配,识别[placeholder]key格式,拆分出属性名和翻译键
  • 属性翻译通过element.setAttribute()设置对应属性值
  • 普通内容翻译保留原有逻辑

修改后,input的placeholder即可正常显示翻译内容,自定义属性也可通过[自定义属性名]翻译键的格式实现翻译。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:06:20