0

I have several .js files each containing different functions and several HTML files showing different parts of the website. I declared a variable in main.js called var lang = "ENG". However, this is the default language in case the user doesn't select a language to change the content of the website. If I were to click a button in index.html:

<button id="french" onclick="changeLang('French')">French</button>

It should change the language of the var lang to "FRE" permanently for the rest of the current browsing period. I have tried using innerHTML, a click listener, a function returning the new value (i.e. var lang = setLanguage(inp), but nothing seems to work. Would anyone please give a suggestion on this? I am working off a large existing code database so I would like something that works in this context (currently not better ways of implementing a "language" facility in the website), although that would certainly be an improvement I would work on long-term. Thanks!

4

2 回答 2

2

如果我理解正确,您希望即使加载新文档也能保留信息。就每个单独的文档而言,没有“程序的持续时间”,但是您可以通过从 sessionStorage 对象写入和读取来跨会话存储数据。

放:

sessionStorage.setItem('language', 'FRE');

得到:

var language = sessionStorage.getItem('language');

您也可以使用 cookie,如果您需要支持旧式浏览器,这可能是必要的。

编辑:在重新阅读您的问题时,我意识到您根本无法设置语言变量,更不用说在整个浏览器会话中设置了。如果是这种情况,我怀疑您遇到了变量范围问题。也许向我们展示 changeLang 函数?例如,如果在全局范围内声明 lang,则设置函数不应使用“var”,否则它将仅在其本地范围内创建一个具有该名称的新变量。

var lang = 'ENG';
function changeLang(newLang) { lang = newlang };
于 2013-01-13T06:07:47.710 回答
1

听起来您的问题与变量范围有关。这是关于 JavaScript 变量作用域的复杂问题:JavaScript 作用域

编辑:如果这不是范围问题,请查看分号的答案。

基本前提是您的lang变量需要是全局变量,然后您应该能够在代码中的其他任何位置修改它。

它应该看起来像这样:

在您的主文件中,在任何函数之外var,使用关键字声明变量,如下所示:var lang = 'ENG';

然后,当您想更改它时(很可能在函数内部)设置变量而不使用var关键字,如下所示:

function changeLanguage(l) {
    lang = l;
}

然后,您应该能够lang在其他任何地方使用并获得最新的值。

于 2013-01-13T06:34:02.447 回答