Tôi đang sử dụng tập lệnh sau cho dự án của mình. Nó cho phép bạn thay đổi ngôn ngữ "lúc chạy", mà không cần tải lại trang. Kịch bản là "autorun", chỉ cần thêm nó vào cuối trang html. Nó có thể có một số lỗi;)
// AutoStar!
// Grab the parameters from my url, and initialize myself! FUGOOOOO
(function __lang_init_wrapper()
{
var scriptSrc = $('script[src*=Lang]').attr('src');
var myParams = parseParams(scriptSrc);
new Lang(myParams.language.toUpperCase(), true);
})();
/**
* Thanks to: http://wowmotty.blogspot.com/2010/04/get-parameters-from-your-script-tag.html
* @param n
* @param s
*/
function gup(n,s){
n = n.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
var p = (new RegExp("[\\?&]"+n+"=([^&#]*)")).exec(s);
return (p===null) ? "" : p[1];
}
/**
*
* @param language The language to use
* @param replaceText If true, replace all the occurency marked with placemark {lang=<key>}
*/
function Lang(language, replaceText)
{
var Languages =
{
ENG:
{
ok: 'ok'
,yes: 'yes'
,no: 'no'
,unknown_user: 'Unknown user'
,too_soon: "It's not time, yet..!"
}
,ITA:
{
yes: 'si'
,unknown_user: 'Utente sconosciuto'
,too_soon: "Pazienta ancora un po'..!"
}
}
// GENERAL SETTINGS
var LANG_CURRENT = language;
var LANG_DEFAULT = 'ENG';
/**
* All the html elements with this attributes are translated on the fly
*/
var LANG_ATTRIBUTE_NAME = "uilang"
/**
* key è la chiave da usare nell'oggetto LANG
* @param key
*/
this.get = function(key)
{
return Languages[LANG_CURRENT][key] || Languages[LANG_DEFAULT][key];
}
/**
* Cerco tutti gli elementi che hanno una certa classe
*/
this.searchAndReplace = function()
{
var me = this;
var divs = $('*[' + LANG_ATTRIBUTE_NAME + ']');
$.each(divs,function(indx,item)
{
item = $(item);
item.text(me.get(item.attr(LANG_ATTRIBUTE_NAME)));
});
}
this.setLanguage = function(language, replaceText)
{
LANG_CURRENT = language;
if(replaceText){
this.searchAndReplace();
}
}
if(replaceText){
this.searchAndReplace();
}
// Returns a localized instance of language
Lang = {
get: this.get
,searchAndReplace: this.searchAndReplace
,setLanguage: this.setLanguage
};
}
Để sử dụng nó, chỉ cần "đánh dấu" một yếu tố html
<h1 uilang="unknown_user"></h1>
hoặc gọi
Lang.get('unknown_user')
để có được những chuỗi cục bộ
Để khởi tạo, hãy gọi cho "hàm tạo"
new Lang("ITA", true);
Để sử dụng nó specifyng một ngôn ngữ,
<script type="text/javascript" src="js/Lang.js?language=ita"></script>
Dường như giải pháp tốt, nhưng tôi không thể truy cập vào localizedResources, chỉ trong dịch mặc định (tiếng Anh) hoạt động. tôi sử dụng công tắc dịch trong tài liệu đã sẵn sàng: $ (document) .ready (function() { \t $ .extend (MyApp.resources, localizedResources); \t}); Và định nghĩa trong đầu sau khi tất cả các kịch bản JS: – redrom
Hãy xem điều này: http://jsfiddle.net/agarcian/rrDv3/1/ Nó hoạt động. – agarcian
đến xấu nó không hoạt động off-line – Astronaut