我对我的语言翻译工具很震惊。 以下是谷歌翻译API的代码。 我必须修改此代码以在文本框中接收来自用户的输入,然后识别输入的语言。目前代码正在从id =“sourceText”中获取值。 我需要在其中放置一个文本框,使其成为一个简单的动态工具。请告诉我应该对添加文本框并接收其输入和检测语言进行哪些修改?感谢...
<html>
<head>
<title>Translate API Example</title>
</head>
<body>
<div id="sourceText">Hello world</div>
<div id="translation"></div>
<script>
function translateText(response) {
document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
}
</script>
<script>
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2/detect?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;
// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
</script>
</body>
</html>
答案 0 :(得分:2)
更改
<div id="sourceText">Hello world</div>
到
<textarea id="sourceText">Hello World</textarea>
同时更新此行:
var sourceText = escape(document.getElementById("sourceText").value);
<html>
<head>
<title>Translate API Example</title>
</head>
<body>
<textarea id="sourceText">Hello world</textarea>
<input type="button" value="Translate" onclick="submit()" />
<div id="translation"></div>
<script>
function translateText(response) {
document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
}
function submit() {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2/detect?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;
// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
}
</script>
</body>
</html>
答案 1 :(得分:0)
如何改变
<div id='mySource'>
进入
<textarea id='mySource'>
并将负责翻译的代码放入功能,并添加一个“trasnalte”按钮,onclick事件会启动翻译功能吗?