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

JavaScript对象内变量更新问题:本地化场景下username无法同步

为啥输入名字后打招呼的话不变?我来教你改!

你现在遇到的问题是:输入名字点“Save changes”后,页面上的打招呼文本还是没显示新输入的名字,一直是空的或者初始值,对吧?

为啥会这样?

举个简单的例子:你提前画了一张卡片,上面写着“早上好,!”(因为最开始你还没填名字),后来你在小本子上写下了自己的名字,但那张提前画好的卡片不会自己变哦——你的代码里,translations里的打招呼文本就是这张提前画好的卡片,一开始username是空的,所以文本就固定成“Good morning, !”了,之后你改了username,这张“卡片”也不会自动更新。

怎么改?

我们换个方式:不要提前把名字写到“卡片”里,而是留个小空位,每次要显示的时候,再把最新的名字填进去。

修改后的完整代码:

HTML部分(基本不用改)
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
</head>
<body>
  <p data-language-key="message">Good morning, {username}!</p>
  <input type="text" placeholder="Type your name...">
  <button>Save changes</button>
</body>
</html>
CSS部分(完全不用改)
body {
  background-color: gray;
}
button {
  margin: 200px;
}
JavaScript部分(重点修改)
var input = document.querySelectorAll("input")[0];
var button = document.querySelectorAll("button")[0];

var locale = "en";
var username = "";

button.onclick = function() {
  username = input.value;
  document.querySelectorAll("[data-language-key]").forEach(translate);
}

function translate(element) {
  const key = element.getAttribute("data-language-key");
  // 先拿到带空位的翻译文本
  let translation = translations[locale][key];
  // 把空位换成最新的名字
  translation = translation.replace("{username}", username);
  element.innerText = translation;
}

var translations = {
  "en": {
    // 这里留空位{username},不直接写死名字
    "message": "Good morning, {username}!",
  },
  "fr": {
    "message": "Bonjour, {username} !",
  }
}

改了哪两处?

  1. 把translations里的文本从带${username}的模板字符串,改成普通字符串,用{username}当空位标记
  2. 在translate函数里,拿到翻译文本后,用replace方法把空位换成当前最新的username值

这样每次点按钮,都会把刚输入的名字填到打招呼的话里,就不会一直是空的啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:45:33