问题
I tried using the code snippet from w3school.com. It worked on w3school but doesnt work on my PC.
<div id="google_translate_element"></div>
<script>
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en'
}, 'google_translate_element');
}
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
I got the following in the console.
translate.html:18 GET file://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit net::ERR_FILE_NOT_FOUND
回答1:
The snippet over at w3school indeed has a bug. It says to add the following line to include Google's API:
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
Unfortunately the trailing // makes it point to a local file. So unless you've downloaded the library and bundled it with your html file this points to nowhere. Instead link to the online library by adding https:
<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
回答2:
When you're running it on your machine, you're running it as a local file. As such, the source file, which is loading from //translate.google
etc, is trying to find this file on google.
If you replace this with:
<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
you will find it is no longer trying to find a local file (i.e. on your machine), but instead will look for it on the internet.
来源:https://stackoverflow.com/questions/57401775/google-translate-javascript-snippet-not-working