简体   繁体   中英

i18next - Language switch is not working properly

I created a language switcher with the i18next js-solution. Everytime i click on the link to change the language, the new language is getting displayed for a second - then the website switches back to the language which is set in the init function.

Does anybody know how I can solve it? I think it has something to do with the document(ready) function, but when i remove this - nothing is working :/

Thank you!

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/i18next-1.7.4.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
      $.i18n.init(
        {
          lng: 'en-US'
        },
        function(t) {
        // translate nav
        $(".nav").i18n();
      });

      $('.changeLng').click(function() {
        $.i18n.setLng("de-DE", function(t) {
          $(".nav").i18n();
        });
      });
    });
    </script>
  </head>
  <body>
    <a href="index.html?setLng=de-DE" class="changeLng">change to de</a>
    <ul class="nav">
      <li>
        <a href="#" data-i18n="nav.home"></a>
      </li>
      <li>
        <a href="#" data-i18n="nav.page1"></a>
      </li>
      <li>
        <a href="#" data-i18n="nav.page2"></a>
      </li>
    </ul>
  </body>
</html>

Try this code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/i18next-1.7.4.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
      $.i18n.init(
        {
          lng: 'en-US'
        },
        function(t) {
        // translate nav
        $(".nav").i18n();
      });

      $('.changeLng').click(function() {
        $.i18n.setLng("de-DE", function(t) {
          $(".nav").i18n();
        });
      });
    });
    </script>
  </head>
  <body>
    <a href="#" class="changeLng">change to de</a>
    <ul class="nav">
      <li>
        <a href="#" data-i18n="nav.home"></a>
      </li>
      <li>
        <a href="#" data-i18n="nav.page1"></a>
      </li>
      <li>
        <a href="#" data-i18n="nav.page2"></a>
      </li>
    </ul>
  </body>
</html>

When you click the link in your version you are reloading the page and the language gets set to 'en-US' again (as the document.ready function gets called again). In this version the page is not reloaded and therefore the language change sticks about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM