用Javascript实现让用户输入用户名和密码,输入正确才可以进入,用户有三次机会
时间: 2024-09-27 19:03:40 浏览: 40
在JavaScript中,你可以创建一个简单的HTML页面结合JavaScript来实现这个功能。这里是一个基本的示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录验证</title>
</head>
<body>
<h2>Login</h2>
<form id="loginForm">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br>
<button type="submit">Login</button>
</form>
<p id="message"></p>
<script>
var attempts = 3;
document.getElementById('loginForm').addEventListener('submit', function(e) {
e.preventDefault();
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
// 模拟检查用户名和密码是否匹配,实际应用中应连接到服务器验证
if (username === 'your_username' && password === 'your_password') {
document.getElementById('message').innerText = "Login successful!";
resetAttempts();
} else {
attempts--;
document.getElementById('message').innerText = `Incorrect. Attempts left: ${attempts}. Try again.`;
if (attempts <= 0) {
document.getElementById('loginForm').style.display = 'none';
document.getElementById('message').innerText = "All attempts exhausted. Please try again later.";
}
}
});
function resetAttempts() {
attempts = 3;
document.getElementById('loginForm').style.display = 'block';
}
</script>
</body>
</html>
```
在这个例子中,我们有一个表单让用户输入用户名和密码,当提交表单时,会检查输入是否正确。如果输入错误,会减少尝试次数并显示剩余尝试次数。当尝试次数达到3次且都失败时,会显示"所有尝试耗尽"的信息,并禁用登录表单。
阅读全文