Google 翻译 API 也在翻译 notranslate class

Google translate API is also translating notranslate class

我这里有以下代码

<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>

What i want is simply ignore the contents of no translate class and dont touch or go inside those classes, but google does not listen.

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

您发送到 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);