我想翻译我的HTML文本

时间:2017-02-27 20:09:41

标签: javascript json html5 translate

我想在我的网站上翻译我使用此代码的文字,我知道我已经接近获得正确的解决方案。

我的HTML代码中的某处:

 <ul class="nav navbar-nav navbar-right">
        <li><a href="#about" data-translate="menu.about">A PREPOS</a></li>
        <li><a href="#services">SERVICES</a></li>
        <li><a href="#portfolio">PORTFOLIO</a></li>
        <li><a href="#pricing">PRICING</a></li>
        <li><a href="#contact">CONTACT</a></li>
        <li>&nbsp;&nbsp;&nbsp;</li>
        <li ><a class="lang">FR</a></li>
        <li ><a class="lang">EN</a></li>
 </ul>

这是我的JavaScript代码:

var dictionary, set_lang;


// Object literal behaving as multi-dictionary
dictionary = {
    "fr": {
        "menu" : {
            "about": "à propos",
            "services": "services"
        }
    },
    "en": {
        "menu" : {
            "about": "about",
            "services": "services"
        }
    }
};

// Function for swapping dictionaries
set_lang = function (dictionary) {
    $("[data-translate]").text(function () {
        var key = $(this).data("translate");
        if (dictionary.hasOwnProperty(key)) {
            console.log(dictionary[key]);
            return dictionary[key];
        }
    });
};

// Swap languages when menu changes
$(".lang").click(function() {
    var language = $(this).html().toLowerCase();
    console.log(language);
    if (dictionary.hasOwnProperty(language)) {
        set_lang(dictionary[language]);
    }
});

// Set initial language to French
set_lang(dictionary.fr);

});

在这部分:

<li><a href="#about" data-translate="menu.about">A PREPOS</a></li>

The Text&#39; A PREPOS&#39;无法翻译,但当我将其更改为:

<li><a href="#about" data-translate="menu">A PREPOS</a></li>

我可以看到我的对象&#39;菜单&#39;使用console.log

3 个答案:

答案 0 :(得分:1)

您的dictionary逻辑完全关闭。 services即:将始终是服务,并且没有充分的理由使用额外的menu层。应避免冗余和重复 而是使用属性,如:

var dictionary = { // props in alphabetical order ok? promise?
  // prop   : {fr, en}
  about     : {fr:"à propos", en:"about"},
  services  : {fr:"services", en:"servicesssss"}
};

function translate( lan ) {

  $("[data-translate]").text(function(){

    var data = this.dataset.translate.split("|");
    var prop = data[0];  // the dictionary property name
    var style = data[1]; // "uppercase", "lowercase", "capitalize"

    if(!prop in dictionary) return console.error("No "+ prop +" in dictionary");

    var trans =  dictionary[prop][lan]; // The translated word

    // Do we need to apply styles?
    if(style==="capitalize"){
       trans = trans.charAt(0).toUpperCase() + trans.slice(1);
    } else if(style==="uppercase"){
       trans = trans.toUpperCase();
    } else if( style==="lowercase"){
       trans = trans.toLowerCase();
    }

    return trans;
  });
}

// Swap languages when menu changes
$("[data-lang]").click(function() {
  translate( this.dataset.lang );
});

// Set initial language to French
translate("fr");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="nav navbar-nav navbar-right">
  <li><a href="#about" data-translate="about|uppercase">A PREPOS</a></li>
  <li><a href="#services" data-translate="services|uppercase">SERVICES</a></li>
  <li>&nbsp;&nbsp;&nbsp;</li>
  <li><a data-lang="fr">FR</a></li>   <!-- data-* attributes can be helpful -->
  <li><a data-lang="en">EN</a></li>
</ul>

答案 1 :(得分:0)

您的问题是,您对dictionary.hasOwnProperty("menu.about")的调用返回false。

你需要遍历对象树,这样你才能获得这样的属性:

dictionary["menu"]["about"]

我已经汇总了一个关于如何遍历对象树的简单递归示例。

&#13;
&#13;
// Object literal behaving as multi-dictionary
dictionary = {
  "fr": {
    "menu": {
      "about": "à propos",
      "services": "services"
    }
  },
  "en": {
    "menu": {
      "about": "about",
      "services": "services"
    }
  }
};

// Function for swapping dictionaries
set_lang = function(dictionary) {
  $("[data-translate]").text(function() {
    var key = $(this).data("translate");
    return parseSubObject(dictionary, key);
  });
};

function parseSubObject(obj, str) {
  var props = str.split(".");
  
  var thisProp = props.shift();
  if (obj.hasOwnProperty(thisProp)) {
    if (props.length == 0) {
      return obj[thisProp];
    } else {
      return parseSubObject(obj[thisProp], props.join('.'));
    }
  } else {
    return null;
  }
}

// Swap languages when menu changes
$(".lang").click(function() {
  var language = $(this).text().toLowerCase();
  if (dictionary.hasOwnProperty(language)) {
    set_lang(dictionary[language]);
  }
});

// Set initial language to French
set_lang(dictionary.fr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="nav navbar-nav navbar-right">
  <li><a href="#about" data-translate="menu.about">A PREPOS</a></li>
  <li><a href="#services">SERVICES</a></li>
  <li><a href="#portfolio">PORTFOLIO</a></li>
  <li><a href="#pricing">PRICING</a></li>
  <li><a href="#contact">CONTACT</a></li>
  <li>&nbsp;&nbsp;&nbsp;</li>
  <li><a class="lang">FR</a></li>
  <li><a class="lang">EN</a></li>
</ul>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您假设dictionary.fr.menu.about提议)与dictionary.fr['menu.about']未定义)相同。

请注意dictionary.fr.menu.about的每个部分的数据结构:

  1. dictionary:对象
  2. dictionary.fr:对象
  3. dictionary.fr.menu:对象
  4. dictionary.fr.menu.about:String
  5. 为了获取String,您需要遍历对象,您可以使用此代码执行:

    set_lang = function(dictionary) {
      $("[data-translate]").text(function() {
        var key = $(this).data("translate").split('.'),
            val = dictionary[key.shift()];
    
        while(key.length) {
          val = val[key.shift()];
        }
        return val;
      });
    };
    

    <强>段:

    var dictionary, set_lang;
    
    
    // Object literal behaving as multi-dictionary
    dictionary = {
      "fr": {
        "menu": {
          "about": "à propos",
          "services": "services"
        }
      },
      "en": {
        "menu": {
          "about": "about",
          "services": "services"
        }
      }
    };
    
    // Function for swapping dictionaries
    set_lang = function(dictionary) {
      $("[data-translate]").text(function() {
        var key = $(this).data("translate").split('.'),
            val = dictionary[key.shift()];
        
        while(key.length) {
          val = val[key.shift()];
        }
        return val;
      });
    };
    
    
    // Swap languages when menu changes
    $(".lang").click(function() {
      var language = $(this).html().toLowerCase();
      console.log(language);
      if (dictionary.hasOwnProperty(language)) {
        set_lang(dictionary[language]);
      }
    });
    
    // Set initial language to French
    set_lang(dictionary.fr);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#about" data-translate="menu.about">A PREPOS</a></li>
      <li><a href="#services">SERVICES</a></li>
      <li><a href="#portfolio">PORTFOLIO</a></li>
      <li><a href="#pricing">PRICING</a></li>
      <li><a href="#contact">CONTACT</a></li>
      <li>&nbsp;&nbsp;&nbsp;</li>
      <li><a class="lang">FR</a></li>
      <li><a class="lang">EN</a></li>
    </ul>