gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:51:31 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com