【问题标题】:how to add google translator for a certain div using jquery如何使用 jquery 为某个 div 添加谷歌翻译器
【发布时间】:2018-01-06 11:05:17
【问题描述】:

我想将谷歌翻译添加到我的网站,如下所示,但它不起作用。虽然我正在添加它不起作用的库。

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

【问题讨论】:

    标签: javascript php jquery html google-translate


    【解决方案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);
      });
     });
    });
    

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2014-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-09
        • 2013-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多