我在这里有以下代码
<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不会听。
有没有办法解决这个问题?
答案 0 :(得分:1)
您向节点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);