单击按钮时Javascript

单击按钮时Javascript

本文介绍了单击按钮时Javascript/Jquery调用Google Translate(带有标志)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有很好的例子可以在HTML页面内使用Google Translate进行翻译?我的意思是,如果我单击德语标志(按钮)而不是翻译成德语等,那么我的问题是如何针对特定语言模拟此组合框? https://www.w3schools.com/howto/howto_google_translate.asp

Is there any good example where I can use Google Translate for translations inside html page? I mean, if I click on german flag (button) than translate to german etc... My question is how to simulate this combo box for specific languages? https://www.w3schools.com/howto/howto_google_translate.asp

谢谢

推荐答案

您可以隐藏此自动创建的选择字段,并通过遍历每个选项字段来搜索所需的语言,从而动态设置其值输入字段.

You can hide this auto-created selection-field and set it's value dynamically by iterating over each option-field to search for the desired language that you can choose via an input-field.

希望这会有所帮助:

<!DOCTYPE html>
<html lang="en-US">
<body>

<h1>My Web Page</h1>

<p>Hello everybody!</p>

<p>Translate this page.</p>

<!-- hide auto-created selection field completely by hiding it's container -->
<div id="google_translate_element" style="display:none"></div>

<p>You can translate the content of this page by selecting a language in the input field.</p>

<!-- flag: you can choose language here: en, de, af etc. -->
<input value="en" id="language"/>
<button onclick="changeLanguageByButtonClick()">Translate</button>

</body>
<script type="text/javascript">

function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: "en"}, 'google_translate_element');
}

function changeLanguageByButtonClick() {
  var language = document.getElementById("language").value;
  var selectField = document.querySelector("#google_translate_element select");
  for(var i=0; i < selectField.children.length; i++){
    var option = selectField.children[i];
    // find desired langauge and change the former language of the hidden selection-field
    if(option.value==language){
       selectField.selectedIndex = i;
       // trigger change event afterwards to make google-lib translate this side
       selectField.dispatchEvent(new Event('change'));
       break;
    }
  }
}
</script>

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

</html>

这篇关于单击按钮时Javascript/Jquery调用Google Translate(带有标志)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:26