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

來源:互聯網
上載者:User

標籤:

關鍵字: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 - Homecommon.text = Welcome!

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

common.title = Loc Sample - Homecommon.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.運行結果:

英文:

中文:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.