Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                    
                
        

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

谢谢

最佳答案

您可以隐藏此自动创建的选择字段,并通过在每个选项字段上进行迭代来动态设置其值,以搜索可以通过输入字段选择的所需语言。

希望这可以帮助:

<!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 - 单击按钮(带有标志)时使用Javascript/Jquery调用Google翻译,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47963066/

10-16 13:08