Google Translate override select change event

末鹿安然 提交于 2019-12-11 09:17:22

问题


I've got a wierd issue:

<div id="translate">
    <a href="#" id="google-translate" title="Google translate">Translate</a>
         <div id="google_translate_element" style="display:none">
         <script>
         function googleTranslateElementInit() {
            new google.translate.TranslateElement({ pageLanguage: "sv" }, "google_translate_element");
         };
         </script>
     </div>
</div>

Which gives me the following:

<div class="skiptranslate goog-te-gadget" style="">
  <div id=":1.targetLanguage">
    <select class="goog-te-combo">
    </select>
  </div>
    Powered by
  <span style="white-space: nowrap;">
  </span>
</div>

I cannot however seem to hijack the change event being triggered when selecting a new language.

I've tried by doing the following:

var $textfield = find("#google-translate");
var $popup = find("#google_translate_element");
var $select = $popup.find("select");

$textfield.click(function () {
    $popup.fadeIn("fast");
    return false;
});

$select.bind("change", function () {
    $popup.fadeOut("fast");
});

Have anyone got a solution for this?

BR, Henric


回答1:


I finally solved this by using a reoccuring check on the language. Not the prettiest solution, but it does the job. :)

var firstMenuValue = $("#main-menu li:first").text();

var checkIfTranslated = function () {
    var check = function () {

        if (firstMenuValue != $("#main-menu li:first").text()) {
            firstMenuValue = $("#main-menu li:first").text();
            $("#google_translate_element").fadeOut("fast");
        }

    };
    setInterval(check, 2000);
};

checkIfTranslated();

I hope this helps out somebody at least.




回答2:


The code below suggested by MjrKusanagi works wonderfully.

$("body").on("change", "#google_translate_element select", function (e) {
    console.log(e);
    console.log($(this).find(":selected").text());
    console.log($(this).find(":selected").val());
});

To view all data inside the drop down

$(".goog-te-combo").find("option").each(function () {
    console.log($(this).text() + ", " + $(this).val() + "\n");
});



回答3:


My guess is that you would need to verify that the HTML from Google has been injected before running your JS code.

I can't seem to find a callback event on the TranslateElement just make a check for a HTML item you know is suppose to be there before running your code. Google Translate Widget - Translation complete callback



来源:https://stackoverflow.com/questions/22562644/google-translate-override-select-change-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!