如何修改此javascript代码以添加文本框并从用户接收输入?

时间:2011-08-06 13:46:33

标签: javascript html

这是Google提供的语言翻译代码,用于检测键入代码的语言。这是默认代码,用于从“var text =”字段转换代码。我想修改此代码,以便在文本框中接收用户的输入,并在单击提交按钮时,它应显示在同一页面上检测到的语言结果。

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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 - Basic Translation</title> 
<script type="text/javascript" src="//www.google.com/jsapi"></script> 
<script type="text/javascript"> 

google.load("language", "1");

function initialize() {
  var text = "¿Dónde está el baño?";
  google.language.detect(text, function(result) {
    if (!result.error) {
      var language = 'unknown';
      for (l in google.language.Languages) {
        if (google.language.Languages[l] == result.language) {
          language = l;
          break;
        }
      }
      var container = document.getElementById("detection");
      container.innerHTML = text + " is: <b>" + language + "</b>";
    }
  });
}
google.setOnLoadCallback(initialize);


</script> 
</head> 
 <body> 
<div id="detection"></div> 
 </body> 
</html>  

1 个答案:

答案 0 :(得分:2)

试试这个

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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 - Basic Translation</title> 
<script type="text/javascript" src="//www.google.com/jsapi"></script> 
<script type="text/javascript"> 

google.load("language", "1");

function initialize(text) {
  google.language.detect(text, function(result) {
    if (!result.error) {
      var language = 'unknown';
      for (l in google.language.Languages) {
        if (google.language.Languages[l] == result.language) {
          language = l;
          break;
        }
      }
      var container = document.getElementById("detection");
      container.innerHTML = text + " is: <b>" + language + "</b>";
    }
  });
  return false;
}


</script> 
</head> 
 <body> 
<form onsubmit="return initialize(this.text1.value">
<input type="text" value="" name="text1" /><input type="submit" />
</form>
<div id="detection"></div> 
 </body> 
</html>