当用户点击西班牙语翻译时切换到其他表单

时间:2013-08-13 18:38:15

标签: javascript jquery forms google-translate

所以我正在使用Google网站翻译器(http://translate.google.com/)来创建我正在创建的网站。

当用户点击西班牙语翻译按钮时,我想切换到另一种形式,但是我无法触发更改,因为html类(translated-ltr)我的基础是更改是动态创建的。

这似乎很容易......但我很困惑。可以这样做吗? 请注意我刚开始学习如何使用javascript / jquery。

Google翻译按钮的代码:

<!-- Spanish Button -->
<a class="translation-links" href="#" class="spanish" data-lang="Spanish" onClick="" onMouseOver="MM_swapImage('spanish.btn','','images/ss_spanish_tout_on.jpg',1)" onMouseOut="MM_swapImgRestore()"><img src="images/ss_spanish_tout.jpg" style="margin-top:10px;" alt="Translate to Spanish!" id="spanish.btn" name="spanish.btn" /></a>

<!-- Code provided by Google -->
<div id="google_translate_element" style="display:none;"></div>
<script type="text/javascript">
  function googleTranslateElementInit() {
    new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'en,es', gaTrack: true, gaId: 'UA-10765676-1', autoDisplay: false}, 'google_translate_element'); //remove the layout
  }
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>


<script type="text/javascript">
    function triggerHtmlEvent(element, eventName) {
var event;
if(document.createEvent) {
    event = document.createEvent('HTMLEvents');
    event.initEvent(eventName, true, true);
    element.dispatchEvent(event);
} else {
    event = document.createEventObject();
    event.eventType = eventName;
    element.fireEvent('on' + event.eventType, event);
}
}
            <!-- Button click handler -->
        $('.translation-links').click(function(e) {
  e.preventDefault();
  var lang = $(this).data('lang');
  $('#google_translate_element select option').each(function(){
    if($(this).text().indexOf(lang) > -1) {
        $(this).parent().val($(this).val());
        var container = document.getElementById('google_translate_element');
        var select = container.getElementsByTagName('select')[0];
        triggerHtmlEvent(select, 'change');
    }
});
});
        </script>

触发表单操作的代码更改:

if ($('html').hasClass('translated-ltr')) {
        $('#contactForm').attr('action', 'kcontactl2_spanish.php');
    }

原始表单链接:

 <form method="post" action="kcontactl2.php" onsubmit="return validateForm();" name="contactSIE" id="contactForm">

1 个答案:

答案 0 :(得分:1)

一种解决方案是使用轮询来检查您要查找的元素是否存在,但我还有其他一些注意事项:

  1. 将javascript事件指定为HTML属性是一个痛苦的世界。这似乎是权宜之计,但事实并非如此。例如,您的链接应转到已翻译的表单,然后您将javascript事件附加到它以取消此行为并动态更改表单。
  2. 如果您打算使用jQuery,也可以使用它来覆盖详细的内置方法,如document.getElementByID。对于其他人来说,读取的内容会更少(例如,在StackOverflow上寻求帮助时)。
  3. 您是否有理由创建自己的事件触发器? JQuery内置了它,它是跨平台的,据我所知,它是无bug的。
  4. 您在javascript中嵌入了HTML评论。这可能会破裂。
  5. 使用css:hover伪类切换图像会更可靠。
  6. 这就是我要这样做的方式:

    <!-- css for the image behind the link -->
    <style type="text/css">
      .translation-links {
         display: inline-block;
         height: 20px; width: 100px; /* modify to the dimensions of the image */
         background: url('images/ss_spanish_tout.jpg') no-repeat center left;
      }
      .translation-links:hover {
         background-image: url('images/ss_spanish_tout_on.jpg');
      }
      .translation-links span {
         visibility:hidden
      }
    </style>
    
    <!-- Spanish Button -->
    <a class="translation-links" href="?lang=spanish" data-lang="Spanish"><span>Translate to Spanish!</span></a>
    
    <!-- Code provided by Google -->
    <div id="google_translate_element" style="display:none;"></div>
    <script type="text/javascript">
      function googleTranslateElementInit() {
        new google.translate.TranslateElement({
            pageLanguage: 'en',
            includedLanguages: 'en,es',
            gaTrack: true,
            gaId: 'UA-10765676-1',
            autoDisplay: false
        }, 'google_translate_element');
      }
    </script>
    <script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>
    
    
    <script type="text/javascript">
       $(function () {
           // translate the form to spanish when the button is clicked
           $('.translation-links').on('click', function(e) {
               var lang = $(this).data('lang'),
                   select = $('#google_translate_element select').first(),
                   // rather than looping the options with $.each, filter them to select 
                   // just what you want.
                   option = select.find('option').filter(function () {
                       return ($(this).text().indexOf(lang) > -1);
                   }).first(); // and take the first, in case there are more than one
               if (option.length) {
                   // I am not quite sure about your use case, but I would change the form
                   // action attribute here, to eliminate the need for the polling block.
                   select.val(option.attr('value')).trigger('change');
               }
               // by putting this at the end, we still have the fallback if the js breaks
               e.preventDefault();
           });
    
           // poll every half a second to see if the form action needs to change
           var html = $('html'), contactForm = $('#contactForm');
           setInterval(function () {
               var url = 'kcontactl2.php';
               if (html.hasClass('translated-ltr')) {
                   url = 'kcontactl2_spanish.php';
               }
               if (contactForm.attr('action') !== url) {
                  contactForm.attr('action', url);
               }
           }, 500);
       });
    </script>