jQuery.i18n.properties 簡介html
請參考此網站:
https://www.ibm.com/developerworks/cn/web/1305_hezj_jqueryi18n/jquery
問題與改進web
資源文件命名問題瀏覽器
在上面的示例中,咱們的程序只自動識別中文和英文兩種翻譯,而不能進一步區分簡體中文與繁體中文。爲了使上面的示例可以根據瀏覽器語言設置自動區分簡體中文和繁體中文,咱們將簡體中文對應的資源文件 strings_zh.properties 重命名爲 strings_zh_CN.properties,並添加如清單 9 所示的繁體中文資源文件 strings_zh_TW.properties。測試
清單 9. strings_zh_TW.properties 1 string_username= 用戶名 2 string_password= 密碼 3 string_login= 登入 4 string_hello= 您好 {0},歡迎使用 jQuery.i18n.properties,您的密鑰是:{1}。 5 string_usernotexist= 用戶不存在 6 string_wrongpassword= 密碼錯誤
運行程序,分別將瀏覽器語言設置爲「中文(簡體中文)」和「中文(繁體中文)」進行測試,發現程序並不能如咱們預期顯示簡體中文和繁體中文,而是都以英文顯示。分析後發現,形成這種現象的緣由,是 jQuery.i18n.properties 插件默認的資源文件命名方式與瀏覽器上報的語言區域編碼不一致,從而致使插件加載資源文件失敗。以簡體中文爲例,jQuery.i18n.properties 默認的資源文件命名方式爲「zh_CN」的形式,而瀏覽器上報的語言區域編碼爲 zh-CN」的形式,此時 jQuery.i18n.properties 插件加載資源文件的步驟以下:網站
加載默認資源文件即 strings.properties,成功。
加載名稱爲 strings_zh.properties 的資源文件,失敗。
加載名稱爲 stirngs_zh-CN.properties 的資源文件,失敗。編碼
因爲第 2 步和第 3 步都失敗,因此 jQuery.i18n.properties 使用默認資源文件 strings.properties 中的翻譯,也就是英文翻譯。同理,繁體中文也不能正常顯示。解決該問題有 3 種方法:插件
1.採用 strings_zh-CN.properties 的方式命名資源文件。這是最簡單的方法,但這種命名方式和 Java 標準的資源文件命名方式不一致;翻譯
2.使用默認的資源文件命名方式,並在調用 jQuery.i18n.properties() 方法以前使用 var lang = jQuery.i18n.browserLang()的方式顯式獲取瀏覽器的語言,而後將 lang 中的「-」替換爲」_」,並在使用 jQuery.i18n.properties() 方法時將 lang 做爲參數。code
3.更改 jQuery.i18n.properties 的源碼。
這裏咱們採用最簡單的第一種方式,將簡體中文對應的資源文件 string_zh_CN.properties 重命名爲 stirngs_zh-CN.properties,並將繁體中文對應的資源文件 strings_zh_TW.properties 重命名爲 strings_zh-TW.properties。如今,程序就能夠根據瀏覽器語言設置自動區分簡體中文和繁體中文了。
對於這個問題,我有另外一種方法:
就是把中英和繁體的資源文件的名字命名以下:
英文:message_en_US.properties
中文簡體:message_zh_CN.properties
中文繁體:message_zh_TW.properties
JS中的處理爲:先獲取當前所選擇的語言,而後再肯定須要獲取哪一種語言資源文件。
代碼以下:
function getErrorMsg(code){ var errorCode="error."+code; var language = $("#language").html(); if ('en'==language) { language = "en_US"; } else if ('zh_CN'==language) { language = "zh_CN"; } else { language = "zh_TW"; } var message = ''; jQuery.i18n.properties({ name:'message', path:'/resources/', mode:'map', language: language, callback: function() { message = $.i18n.prop(errorCode); } }); return message; }
每次jQuery.i18n.properties鏈接的時候會把name拼接上"_"再拼接上language,而後去查詢path下時候有對應的properties文件,好比language爲中文繁體,則查詢message_zh_TW.prperties。