最好不要从 JavaScript 中解决这个问题。话虽这么说,作为一项学术和学习练习,这只是一个粗略的想法,告诉你如何去做这样的事情:
<select id="lang">
<option>English</option>
<option>Portuguese</option>
<option>Russian</option>
</select>
<span data-translate="_hello">Hello</span>,
<span data-translate="_january">January</span>!
// Some variables for later
var dictionary, set_lang;
// Object literal behaving as multi-dictionary
dictionary = {
"english": {
"_hello": "Hello",
"_january": "January"
},
"portuguese": {
"_hello": "Oie",
"_january": "Janeiro"
},
"russian": {
"_hello": "привет",
"_january": "январь"
}
};
$(function () {
// Lets be professional, shall we?
"use strict";
// Function for swapping dictionaries
set_lang = function (dictionary) {
$("[data-translate]").text(function () {
var key = $(this).data("translate");
if (dictionary.hasOwnProperty(key)) {
return dictionary[key];
}
});
};
// Swap languages when menu changes
$("#lang").on("change", function () {
var language = $(this).val().toLowerCase();
if (dictionary.hasOwnProperty(language)) {
set_lang(dictionary[language]);
}
});
// Set initial language to English
set_lang(dictionary.english);
});
小提琴:http: //jsfiddle.net/MBRG4/5/