3

因此,我正在为我正在创建的网站使用 Google 网站翻译器 ( http://translate.google.com/ )。

当用户单击西班牙语翻译按钮时,我想切换到不同的表单,但我无法触发更改,因为我基于更改的 html 类 (translated-ltr) 是动态创建的.

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

谷歌翻译按钮的代码:

<!-- 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">
4

1 回答 1

1

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

  1. 将 javascript 事件指定为 HTML 属性是一个痛苦的世界。这似乎是权宜之计,但事实并非如此。例如,您的链接应该转到已翻译的表单,然后您将 javascript 事件附加到它以取消此行为并动态更改表单。
  2. 如果您打算使用 jQuery,不妨使用它来覆盖诸如 document.getElementByID 之类的冗长的内置方法。其他人阅读起来会不那么刺耳(例如,在 StackOverflow 上寻求帮助时)。
  3. 您是否有理由创建自己的事件触发器?JQuery 内置了这个,它是跨平台的,据我所知没有错误。
  4. 您在 javascript 中嵌入了 HTML 注释。这可以打破。
  5. 使用 css :hover 伪类切换图像会更可靠。

我会这样做:

<!-- 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>
于 2013-12-10T10:17:38.527 回答