如何使用jquery为某个div添加谷歌翻译器

时间:2018-01-06 11:05:18

标签: javascript php jquery html5 google-translate

我想将谷歌翻译添加到我的网站,如下所示,但它不起作用。尽管添加了它不起作用的库。

<p id="some">Hello</p>
<input id="trans" value="Translate" type="button">
<script>
 $('#trans').click(function() {
    google.language.translate($('#some').html(), 'en', 'fr',  function(result)         {
       $('#some').html(result.translation);
   });
 });
</script>
 <script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

我收到了这个错误:

Uncaught TypeError: Cannot read property 'translate' of undefined at 
HTMLInputElement.eval (eval at <anonymous> (jquery-1.10.2.js?673:612), 
<anonymous>:4:18) at HTMLInputElement.dispatch (eval at <anonymous> (jquery-
1.10.2.js?673:612), <anonymous>:5095:9) at HTMLInputElement.elemData.handle 
(eval at <anonymous> (jquery-1.10.2.js?673:612), <anonymous>:4766:28) 

2 个答案:

答案 0 :(得分:1)

尝试将事件侦听器包装在document load中,以便在加载库后初始化google.language.translate

$(document).ready(function(){

 $('#trans').click(function() {
  google.language.translate($('#some').html(), 'en', 'fr',  function(result)         
  {
     $('#some').html(result.translation);
  });
 });
});
  

在文档准备好之前,页面无法安全操作。&#34; jQuery为您检测这种准备状态。 $( document ).ready()中包含的代码只有在页面文档对象模型(DOM)准备好执行JavaScript代码后才会运行。 $( window ).on( "load", function() { ... })内包含的代码将在整个页面(图片或iframe)(而不仅仅是DOM)准备就绪后运行。

答案 1 :(得分:0)

尝试使用jquery的on方法。例如:

$( "#trans" ).on( "click", function() {
   //invoke your method here.
});