1

当用户单击我网页上的按钮时,我已经能够使用带有 AJAX 调用的 Microsoft 翻译 API 将一段从英语翻译成西班牙语。我想让他们能够切换回原始文本,而无需将西班牙语文本翻译回英文。当我查看页面源代码时,我可以看到原始文本,但我不确定如何将其显示给用户。

function Translate()
{
  var from = "en", to = "es", text = $('.Translate').text();
  
  var s = document.createElement("script");
  s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
      "?appId=Bearer " + encodeURIComponent(window.accessToken) +
      "&from=" + encodeURIComponent(from) +
      "&to=" + encodeURIComponent(to) +
      "&text=" + encodeURIComponent(text) +
      "&oncomplete=MyCallback";
  document.body.appendChild(s);
}

function MyCallback(response)
{
  $('.Translate').text(response);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnTranslate" onclick="Translate()" class="etsButton">Translate</button>
<button id="btnRestore" onclick="Restore()" class="etsButton">Restore</button>

<div style="padding:10px;" class="Translate">
To be, or not to be: that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them? 
</div>

4

2 回答 2

2

查看页面源代码不会显示页面的当前 HTML。问题是您的行$('.Translate').text(response);破坏了页面上的原始文本。

如果您希望能够切换回来,那么您需要将翻译后的文本放入一个新的 div 中。然后你可以只显示和隐藏 div 以在显示的版本之间切换。

于 2015-09-09T21:16:13.927 回答
1

您可以通过将原始文本存储在变量中来在翻译之前记住原始文本,然后在restore()函数中您可以替换text为该变量的内容。但是因为这个临时变量应该在不同的函数中设置和获取它的值,所以它应该在更高的范围内。在您的情况下,它将是全球性的,但请记住,不建议这样做。

var originalText; 

function Translate()
{
  var from = "en", to = "es", text = $('.Translate').text();

  originalText = text;

  var s = document.createElement("script");
  s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
      "?appId=Bearer " + encodeURIComponent(window.accessToken) +
      "&from=" + encodeURIComponent(from) +
      "&to=" + encodeURIComponent(to) +
      "&text=" + encodeURIComponent(text) +
      "&oncomplete=MyCallback";
  document.body.appendChild(s);
}

function restore(){
   $('.Translate').text(originalText);
}
于 2015-09-09T21:16:40.700 回答