开发者

Google Ajax Language translation question

I'm trying to figure out how to use Google's code to translate text ONLY if it is NOT English. The code below works if you enter Spanish or another foreign language, but it just repeats English if English is entered (obviously we don't need English translated). Any ideas? Thx.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Google Ajax Language API</title>
</head>

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
      var text = document.getElementById("text").innerHTML;
      google.language.detect(text, function(result) {
        if (!result.error && result.language)  {
          google.language.translate(text, result.language, "en",
                                    function(result) {
            var translated = document.getElementById("translation");
            if (result.translation) {
           开发者_JS百科   translated.innerHTML = result.translation;
            }
          });
        }
      });
    }
    google.setOnLoadCallback(initialize);
</script>


<body>


<div style="width:420px; margin:auto; padding:5px;">Original Text:</div>
<div id="text" style="width:420px; margin:auto; padding:5px;">I like cold beer</div>
<br />
<div style="width:420px; margin:auto; padding:5px;">Translated Text:</div>
<div id="translation" style="width:420px;margin:auto;padding:3px;"></div>



</body>
</html>


detect tells you the language. Just take advantage of that to do nothing if the language is 'en'

if (!result.error && result.language && result.language != 'en')  {
          google.language.translate(text, result.language, "en",
                                    function(result) {
            var translated = document.getElementById("translation");
            if (result.translation) {
              translated.innerHTML = result.translation;
            }
          });
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜