jQuery语言切换器
我想建立一个网站,其内容有两种语言。 我想使用jQuery进行语言切换。 我的想法是这样的:
而不是HTML页面中的实际内容:
Hello there
我想使用类:
HTML:
JS(我不擅长JS;我把它与一些PHP相结合,所以我可以让自己理解):
var EN = new array('hello_EN' => 'Hello there'); foreach($EN as $class => $content) $(".$class").text("$content"); //this should populate all my HTML classes with its content
然后,我必须有我的第二语言数组:
var RO = new array('hello_RO' => 'Salut');
现在,切换:
$("#change_to_RO").click(function() { $(EN).replaceWith(RO); });
我该怎么办呢? 谢谢。
最好不要从JavaScript中解决这个问题。 话虽这么说,作为一个学术和学习练习,这里只是一个粗略的想法,你可以如何做这样的事情:
Hello, January!
// 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/