在JavaScript中,回车键(Enter键)通常用于提交表单或触发某个事件。当用户在输入框中按下回车键时,浏览器会尝试提交表单或执行与该输入框关联的事件处理程序。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Submission with Enter Key</title>
</head>
<body>
<form id="myForm" action="/submit" method="post">
<input type="text" id="username" name="username" placeholder="Username">
<input type="password" id="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // 阻止默认提交行为
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
console.log('Username:', username);
console.log('Password:', password);
// 这里可以添加你的提交逻辑,例如使用AJAX发送数据
});
</script>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Trigger with Enter Key</title>
</head>
<body>
<input type="text" id="searchInput" placeholder="Search...">
<div id="searchResults"></div>
<script>
document.getElementById('searchInput').addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault(); // 阻止默认行为
const searchTerm = this.value;
console.log('Searching for:', searchTerm);
// 这里可以添加你的搜索逻辑,例如调用API获取搜索结果
document.getElementById('searchResults').innerText = `Results for: ${searchTerm}`;
}
});
</script>
</body>
</html>原因:
type属性未正确设置。解决方法:
type属性正确设置(例如type="text")。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Submission with Enter Key</title>
</head>
<body>
<form id="myForm" action="/submit" method="post">
<input type="text" id="username" name="username" placeholder="Username">
<input type="password" id="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // 阻止默认提交行为
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
console.log('Username:', username);
console.log('Password:', password);
// 这里可以添加你的提交逻辑,例如使用AJAX发送数据
});
</script>
</body>
</html>通过以上代码,确保表单在按下回车键时能够正确提交。
没有搜到相关的文章