Build multiple language website using jQuery and JSON based methods

后端 未结 3 1487
太阳男子
太阳男子 2021-01-05 21:57

I\'m trying to implement a Multi-language for one website. I prefer to use client script for changing the language between English and Tr

3条回答
  •  滥情空心
    2021-01-05 22:44

    You can save the user's selected language with window.localStorage and read it when you load the page:

    // save, in your .translate click handler
    localStorage.setItem('lang', $(this).attr('id'));
    
    // load, on DOMContentLoaded
    var lang = localStorage.getItem('lang') || 'en-gb';
    

    If the user hasn't selected a language, localStorage.getItem('lang') will return null and lang will be set to your default, 'en-gb'.

    But why should your default be English? The browser knows what language it (and presumably, the user) prefers. You can access the browser's preferred language with navigator.language. Of course, that could be something like zh-SG which isn't in your language list, but should (probably?) render the page in Chinese. To handle this behavior, you can grab just the first two characters of the language code and use that as the key in your strings list:

    var arrLang = {
        "en": {
            "HOME": "Home",
            "ABOUT": "About Us",
            "CONTACT": "Contact Us",
        },
        "zh": {
            "HOME": "首頁",
            "ABOUT": "關於我們",
            "CONTACT": "聯絡我們",
        }
    };
    
    var lang = localStorage.getItem('lang') || navigator.language.slice(0, 2);
    

    (You'll need to truncate the IDs of your translate buttons, as well.)

    Of course, the browser's language could be pt-BR, so make sure to check for that too:

    var lang = localStorage.getItem('lang') || navigator.language.slice(0, 2);
    if (!Object.keys(arrLang).includes(lang)) lang = 'en';
    

提交回复
热议问题