【问题标题】:Google translate API is also translating notranslate class谷歌翻译 API 也在翻译 notranslate 类
【发布时间】:2020-12-19 07:35:54
【问题描述】:

我这里有以下代码

<body>
    <p id="textField">You can translate the <span class="notranslate"  translate="no" >content of this page</span> by selecting a language in the select box.</p>
    <h1 id="title">My Web Page</h1>
    <p>Hello everybody!</p>
    <p>Translate this page:</p>
    <form>
        <select id="targetLanguage">
            <option value="en">English</option>
            <option value="hi">Hindi</option>
        </select>

        <input type="button" id="translateButton" value="Translate" />
    </form>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("#translateButton").click(function () {

            var url = "https://translation.googleapis.com/language/translate/v2";
            //Strings requiring translation
            url += "?q=" + $("#textField").text();
            url += "&q=" + $("#title").text();
            //Target language
            url += "&target=" + $("#targetLanguage").val();
            //Replace with your API key
            url += "&key=API_KEY_if You need to test i can share";
            $.get(url, function (data, status) {
                //Results are returned in an array following the order they were passed. 
                $("#textField").text(data.data.translations[0].translatedText);
                $("#title").text(data.data.translations[1].translatedText);
            });       
        });
    </script>  
</body>

我想要的只是忽略没有翻译类的内容和 不要触摸或进入这些课程,但谷歌不听。

有什么办法可以解决这个问题吗??

【问题讨论】:

    标签: google-api google-translate translate google-translation-api


    【解决方案1】:

    您向 Google api 发送您的节点文本内容,而不是发送 HTML。

    将您的代码(第 20-22 行)替换为:

    //Strings requiring translation
    url += "?q=" + encodeURIComponent($("#textField").html());
    url += "&q=" + encodeURIComponent($("#title").html());
    

    .text() jQuery 方法将只检索目标元素的文本内容,删除所有 html。 但是您想发送 HTML,因为您需要 Google 检索 translate="no" 属性以避免翻译这部分文本。

    另外,我建议使用 encodeURIComponent 函数对您将通过查询字符串发送的 html 进行编码。 如果您的 html 包含特殊字符(如 &

    ),它将防止出现意外行为

    您还必须使用 html() 方法而不是文本来替换您的内容。

    $("#textField").html(data.data.translations[0].translatedText);
    $("#title").html(data.data.translations[1].translatedText);
    

    【讨论】:

      猜你喜欢
      • 2011-12-26
      • 2016-11-18
      • 2010-10-10
      • 1970-01-01
      • 2011-06-06
      • 2015-09-27
      • 2013-02-15
      相关资源
      最近更新 更多