<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>
开发人员:Desmond Ouckama
如您所知,这应该是莫尔斯电码翻译器。当您实际单击该按钮时,脚本可以完美运行,但是当我按Enter键时,它会在一秒钟内显示正确的翻译,然后刷新页面。我不太确定发生了什么。
最佳答案
当您按Enter键时,您正在提交表单。您要做的就是阻止表单提交:
document.querySelector('form').addEventListener('submit',function(e){
e.preventDefault();
});
关于javascript - 在运行相应的脚本后的一秒钟内,“输入键”单击按钮正在刷新页面,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44007648/