2010-06-26 140 views
1

我想知道如何使用Google的代碼翻譯文本,只要它不是英文。如果您輸入西班牙語或其他外語,下面的代碼可以正常工作,但如果輸入英語,它只是重複英語(顯然,我們不需要英語翻譯)。有任何想法嗎?謝謝。Google Ajax語言翻譯問題

<!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) { 
       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> 

回答

2

detect告訴你語言。只要利用這一點,如果語言是'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

工程!哇,快點..... – Barry 2010-06-26 03:42:52