gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:39:34 25 4
gpt4 key购买 nike

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

开发商:德斯蒙德·乌卡马

正如你所知,这应该是一个莫尔斯电码翻译器。当您实际单击该按钮时,脚本运行得很好,但是当我按回车键时,它会立即显示正确的翻译,然后刷新页面。我不太确定发生了什么事。

最佳答案

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

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

关于javascript - "enter key"单击按钮在运行相应脚本后瞬间刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44007648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com