3

そのため、作成中のウェブサイトに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">
4

1 に答える 1

1

1 つの解決策は、ポーリングを使用して、探している要素が存在するかどうかを確認することですが、他にもいくつか注意事項があります。

  1. JavaScript イベントを HTML 属性として指定するのは苦痛の世界です。便利なようですが、そうではありません。たとえば、リンクは翻訳されたフォームに移動する必要があり、JavaScript イベントをそれに添付して、この動作をキャンセルし、フォームを動的に変更します。
  2. jQuery を使用する場合は、それを使用して、document.getElementByID などの冗長な組み込みメソッドをオーバーライドすることもできます。他の人が読むのに不快感が少なくなります (たとえば、StackOverflow で助けを求めるとき)。
  3. 独自のイベント トリガーを作成する理由はありますか? JQueryにはこれが組み込まれており、クロスプラットフォームであり、私の知る限りバグはありません。
  4. HTML コメントが JavaScript に埋め込まれています。これは壊れる可能性があります。
  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 に答える