我正在为一个包含多种语言内容的网站编写一些 JavaScript。我想使用 Google Translate API 来允许用户选择一个单词(或短语)并自动提供翻译。目前,我只是让它提醒测试结果。
这是我到目前为止所拥有的: google.load("语言", "1");
function getSelection() {
var selection = (!!document.getSelection) ? document.getSelection() :
(!!window.getSelection) ? window.getSelection() :
document.selection.createRange().text;
if (selection.text)
selection = selection.text
console.log(selection);
return selection
}
$(document).ready(function() {
$(window).mouseup(function() {
var selection = getSelection();
if (selection != "") {
google.language.translate(selection, "", "en", function(result) {
if (!result.error) {
alert(result.translation);
} else {
alert(result.error);
}
});
}
});
});
我遇到的问题是我的 getSelection() 函数返回 Range 对象,这显然与 google 的 language.translate() 函数不兼容。我真正需要的是一种从 Range 中检索实际文本作为字符串的方法,这样我就可以传递它。据我所知,有一些非常简单、明显的方法可以做到这一点,但我只是缺少它(是的,我尝试使用selection.text),但我对 JavaScript 的经验有限,谷歌搜索没有透露任何有用的东西。
有人可以帮忙吗?
最佳答案
尝试 jQuery 谷歌翻译 - http://code.google.com/p/jquery-translate/ .
关于javascript - 使用 Google Translate API(和 jQuery)翻译用户选择的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1719402/