jQuery中变量的动态连接

时间:2014-08-27 10:09:10

标签: jquery concatenation

我正在尝试根据url中的参数动态更改某些h1文本。我不确定如何将文本连接在一起以创建一个新变量。

这是我的代码:

$.getScript("/js/bannerText.js", function(){
    var mainTitle = prefLang+'Main';
    console.log(mainTitle); // I want this to be "Main Text English"
});

在bannerText.js中我有不同的翻译:

var enMain  =   "Main Text English";
var enSub   =   "Sub Text English";

prefLang从网址获取语言代码。在这种情况下,它是en。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用JavaScript括号表示法[]来访问具有变量名称的变量:

// declare some global variables
var foo = 'foo value';
var bar = 'bar value';
var baz = 'baz value';

// <parenthesis>
// For information, the line below (when executed in global scope ONLY):
var x = 'x'
// is equivalent to this:
window.x = 'x'
// </parenthesis>


// choose what variable you want to use
var varName = 'bar';


// use 'varName' to retrieve the value
var theValue = window[varName];
console.log(theValue);

// here's the step by step of what's happening
theValue = window[varName];
// equals to
theValue = window['bar'];
// which get executed as
theValue = window.bar;
// which is the same as (see parenthesis above)
theValue = bar ;
// then finally
theValue = 'bar value';

所以,你的问题可以解决如下:

// declare some global variables
var enMain  =   "Main Text English";
var enSub   =   "Sub Text English";

// choose what variable you want to use
var prefLang = 'en';
var varName = prefLang+'Main';

// use 'varName' to retrieve the value
var mainTitle = window[varName];
console.log(mainTitle); // "Main Text English"

但是,我认为您正在进行一些内部化过程,如果没有外部库的帮助,我会这样做:

// step 1) declare all your texts

var availableTexts = {
};

availableTexts.en = {
    Main: "Main Text English",
    Sub: "Sub Text English",
};
availableTexts.es = {
    Main: "Texto principal Español",
    Sub: "Texto secundario Español",
};
availableTexts.fr = {
    Main: "Texte principal en français",
    Sub: "Texte secondaire en français",
};
// and so on...


// step 2) get the value from URL
// I hard code it here just for the demo
var prefLang = 'en';
// define a fallback language if the language
// you're looking for does not exist
var defaultLang = 'en';


// step 3) retrieve all the values, localized according to prefLang value
// if not found, fall back to the values of defaultLang
var localizedText = availableTexts[prefLang] || availableTexts[defaultLang];


// step 4) in all your code, you just have to use the variable localizedText
// now you don't care what the user language is,
// and you keep your code so dead simple by the way !
$.getScript("/js/bannerText.js", function(){
    console.log(localizedText.Main); // "Main Text English"
});