点击按钮后显示Google翻译小部件 [英] Display Google translate widget after button click

查看:177
本文介绍了点击按钮后显示Google翻译小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在点击按钮后加载并显示Google翻译小部件。如何做到这一点?

I need to load and display the Google translate widget after a button was clicked. How to do that?

<div id="google_translate_element"></div><script>
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en',
    layout: google.translate.TranslateElement.InlineLayout.SIMPLE
  }, 'google_translate_element');
}
</script><script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

顺便说一句:它在 // strong> // translate.google.com ?

Btw: What is it with that // URL they used in //translate.google.com?

推荐答案

如果你使用jQuery,你可以添加一个按钮在google_translate_element中,并使用getScript从Google加载翻译脚本,并在点击该按钮后才运行googleTranslateElementInit函数。

If you are using jQuery, you can add a button in the google_translate_element and use getScript to load the translate script from Google and run the googleTranslateElementInit function only after the button is clicked.

$("#google_translate_element button").click(function(){
    $(this).hide();
    var url = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    $.getScript(url);   
});

保留原始问题中显示的代码,但删除<脚本src =// translate.google.com/translate_a/element.js?cb=googleTranslateElementInit\"></script> ,因为这是您想要抑制页面加载并启动按钮点击。

Maintain the code as shown in the original question but remove the <script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script> as that is what you want to suppress on the page load and initiate on the button click.

如果您想在google_translate_element之外的其他地方添加按钮,您必须调整或移除 $(这个).hide(); 上面代码的一部分。

if you want to add a button somewhere other than within the google_translate_element, you'll have to adjust or remove the $(this).hide(); part of the above code.

这样可以节省大量的页面加载时间,脚本需要花费很多时间来加载。以这种方式使用它可以避免在默认情况下加载它,只有在用户请求时才会添加。

This saves a significant amount of time on the page load as the Google Translate script takes a lot of time to load. Using it in this way avoids loading it by default and is only added if the user requests it.

这篇关于点击按钮后显示Google翻译小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆