问题
I am facing a little strange problem. I am using bing translator (http://www.bing.com/widget/translator) and trying to customize it on my own using their API.
Here is my code for testing purposes.
Script:
$(document).ready(function (e) {
var lang;
$('#changeLang a').click(function (e) {
Microsoft.Translator.Widget.Translate(null, 'en', null, null, function () {
lang = Microsoft.Translator.Widget.GetAutoDetectedLanguage();
alert(lang)
});
document.getElementById('WidgetFloaterPanels').style.display = 'none';
var to = $(this).attr('id');
if (to == "en") {
Microsoft.Translator.Widget.Translate(lang, 'en');
document.getElementById('WidgetFloaterPanels').style.display = 'none';
} else if (to == "ja") {
Microsoft.Translator.Widget.Translate(lang, 'ja');
document.getElementById('WidgetFloaterPanels').style.display = 'none';
} else if (to == "fr") {
Microsoft.Translator.Widget.Translate(lang, 'fr');
document.getElementById('WidgetFloaterPanels').style.display = 'none';
} else if (to == "ru") {
Microsoft.Translator.Widget.Translate(lang, 'ru');
document.getElementById('WidgetFloaterPanels').style.display = 'none';
}
});
}); //ready ends
HTML:
<div id="changeLang">
<a href="#" id="en">English</a>
<a href="#" id="ja">Japenese</a>
<a href="#" id="fr">French</a>
<a href="#" id="ru">Russia</a>
</div>
<div>This paragraph needs to be translated</div>
Now, the script is working fine as it should but for the first two times. For example, if i click on Japenese, the page would translate accordingly, and if i click back to english or any other language, the page will be translated accordingly. But after the second time, if i click third time on any language. The function does not work. But it should work like it was working in the first two clicks. I have tried several hours but can't get it to work so i opened the questions. Please someone point it out to me what is wrong.
回答1:
It seems that Microsoft script changes the HTML structure during the translation process. Because of this you have to use delegation: instead of $("#changeLang a").on("click", handler)
you will do $('#changeLang').on("click", "a", handler)
. Also, your code can be simplified:
var lang;
$('#changeLang').on("click", "a", function (e) {
var to = $(this).attr('id');
console.log("Translating from ", lang, " to ", to);
Microsoft.Translator.Widget.Translate(lang, to);
lang = to;
});
JSFIDDLE
来源:https://stackoverflow.com/questions/20772651/jquery-click-handler-not-working-after-two-times