I have been able to translate a paragraph from English to Spanish using the Microsoft translator API with an AJAX call when a user clicks a button on my webpage. I would like to give them the ability to toggle back to the original text without having to translate the Spanish text back to English. When I view the page source I can see the original text, but I am not sure how to display that back to the user.
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>
Viewing the page source does not show you the current HTML for the page. The problem is that your line $('.Translate').text(response);
destroys the original text that was on your page.
If you want to be able to switch back, then you need to put the translated text into a new div. Then you can just show and hide the divs to toggle between the displayed version.
You can remember original text before translating it by storing it in a variable, and then in restore()
function you can replace text
with the content of this variable. But because this temporary variable should set and get it`s value in different functions, it should be in a higher scope. In your case it would be global one, but keep in mind that is not recommended.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.