2017-05-16 7 views
1
<html> 
<head> 
    <title>Morse Code Translator</title> 

    </head> 
<body> 
    <h3>English to Morse Code Translator</h3> 
    <hr /> 
    <form name = "morseCodeTranslator"> 

     <!--This is where it should wait for the enter key--> 



     Enter your word or phrase: <input type = "text" name = "inputs" value="" id = "yourWord" onkeydown = "if (event.keyCode == 13) document.getElementById('btnSearch').click()" size = "5"> 
     <input class = "button" type = "button" value="Translate!" onclick="trans()" id = "btnSearch"> 
    </form> 
    <h6>You can also press the enter key to translate.</h6> 
    <hr /> 
    <script> 
    function trans(){//function called by the button 
     //get the input 
     var yourWord = document.getElementById("yourWord").value; 
     //the alphabet 
     var alphabet = "abcdefghijklmnopqrstuvwxyz "; 
     //Get everything lowercase 
     yourWord = yourWord.toLowerCase().replace(/[^a-z]/g, ""); 
     //declare the morse code array 
     var morseCode = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-",  ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]; 
     //variables to help out in the loop 
     var i; 
     var c; 
     var x; 
     //the first loop for each letter of the input 
     for(i = 0; i < yourWord.length; i++){ 
      c = yourWord.charAt(i); 
      for(x = 0; x < 27; x++){ //the next loop for each letter of the alphabet 
       if(c == alphabet.charAt(x)){ //match? 
        var d = document.createElement("div"); // Creates a new <div> node 
        d.textContent = morseCode[x] + " | ";   // Sets the text content 
        document.body.appendChild(d); 
       } 
      } 
     } 
    } 
    </script> 

開発実行した後に、第2の分割さわやかなページです:デズモンドOuckama ボタンをクリックし、「キーを入力するには、」対応するスクリプトを

をこれは、あなたが言うことができるように、モールス信号翻訳することになっています。実際にボタンをクリックすると、スクリプトは完璧に動作しますが、Enterキーを押すと、1秒間の正しい翻訳が表示され、ページが更新されます。私は本当に何が起こっているのか分かりません。

+0

これはフォームを送信しているためです。 onsubmitイベントをキャプチャしてpreventDefaultまたはjsutフォームタグを削除することができます。これは、フォームを送信する場合にのみ必要です。 –

答えて

1

Enterキーを押すと、フォームが送信されます。

document.querySelector('form').addEventListener('submit',function(e){ 
    e.preventDefault(); 
}); 
+1

うわー。ありがとうございました。それは簡単だった。 – Dez

0

入力すると、ボタンのクリックをシミュレートするだけです。フォーム内のボタンには、デフォルトの動作が「submit」として設定されています。ボタンの属性にtype=buttonを追加して変更することができます

<button class = "button" type="button" onclick="trans()" id = "btnSearch">Translate!</button> 
+0

彼は 'input'を' button'ではなく使用しています –

+0

彼は私が書いたコードのようにボタンの入力を入れ替えることができました –

関連する問題