"enter key"单击按钮是在运行相应脚本后的一瞬间刷新页面


<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>

开发商: 戴斯蒙德·奥卡马

正如你所知道的,这应该是一个莫尔斯电码转换器。当您实际单击该按钮时,脚本可以完美运行,但是当我按 Enter 时,它会在一瞬间显示正确的翻译,然后刷新页面。我不太确定发生了什么。

当您按回车键时,您正在提交表单。您所要做的就是阻止表单提交:

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

当您输入时,您可以模拟按钮单击。表单内的任何按钮的默认行为都设置为"提交"。您可以通过向按钮的属性添加type=button来更改它

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

最新更新