本地化web開發的一個例子-jquery.i18n.properties


關鍵字:Web本地化, jquery,jquery.i18n.properties。

運行環境:Chrome, IE。

 

本文介紹使用jquery.i18n.properties對網站前端實現本地化,支持多語言。網站內容根據瀏覽器設置的語言來顯示。

1.前端文件夾結構如下:

2.index.html文件

<!DOCTYPE html>
<html>
<head>
    <title data-localize="common.title"></title>
    
    <script src="/javascripts/3p/jquery-1.8.2.min.js"></script>
    <script src="/javascripts/3p/jquery.i18n.properties-min-1.0.9.js"></script>
    <script src="/javascripts/main.js"></script>
</head>

<body>
    <div class="home-area" id="home" data-localize="common.text"></div>
</body>
</html>

需要本地化common.title和common.text。

3.properties

main.properties是被默認使用如果沒有找到匹配的語言。

common.title = Loc Sample - Home
common.text = Welcome!

main_en.properties,如果瀏覽器語言是en_*,該文件將被使用。

common.title = Loc Sample - Home
common.text = Welcome!

main_zh.properties,如果瀏覽器語言是zh_*,該文件將被使用。

common.title = Loc Sample - 主頁
common.text = 歡迎光臨!

4.main.js

$(document).ready(function(){
    loadProperties('main', '/strings/main/');
});

function loadProperties(name, path, lang){
    var lang = lang || navigator.language;
    jQuery.i18n.properties({
        name:name, 
        path:path,
        mode:'map',
        language: lang,
        callback: function() {
            $("[data-localize]").each(function() {
                var elem = $(this),
                    localizedValue = jQuery.i18n.map[elem.data("localize")];
                
                if (elem.is("input[type=text]") || elem.is("input[type=password]") || elem.is("input[type=email]")) {
                    elem.attr("placeholder", localizedValue);
                } else if (elem.is("input[type=button]") || elem.is("input[type=submit]")) {
                    elem.attr("value", localizedValue);
                } else {
                    elem.text(localizedValue);
                }
            });
        }
    });
}

loadProperties函數在頁面加載完畢后被調用。loadProperties根據瀏覽器語言來找到匹配的properties文件,然后替換頁面字符串內容。

5.建立一個web服務器來運行index.html。

直接打開index.html,會有跨域訪問的問題,導致不能訪問properties文件。

所以需要建立一個web服務器。如何建立web服務器請參考:http://www.cnblogs.com/ldlchina/p/4054974.html

6.運行結果:

英文:

中文:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM