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

标签 javascript php jquery html 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) 

最佳答案

尝试将事件监听器包装在 document load 中,因此 google.language.translate 将在库加载后初始化:


$(document).ready(function(){

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

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

关于javascript - 如何使用 jquery 为某个 div 添加谷歌翻译器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48126696/

相关文章:

javascript - 如何使用node.js打开服务器上的文件

php - 选择所有行,分组依据

php - 有什么方法可以在我的 Web 应用程序中提供不同的视频质量,而无需将每个视频转换为每种格式?

jquery - 在 Internet Explorer 中获取图像的宽度和高度

JavaScript:谷歌地图mapOptions?

javascript - 将谷歌电子表格扩展到谷歌网络应用程序

javascript - Binance API 和 angular 4 httpClient

javascript - 为什么 jquery 自动完成功能不起作用?

php - 从 DOM 对象中删除跨度但不删除内容并将其保存到变量中

javascript - 如何基于选项按钮启用和禁用文本框多个字段