据我了解,您将只有 3 个可能登录的预定义用户。我假设您只想展示应用程序的功能,而不是构建防弹登录系统。为此,您可以使用如下形式:
<form>
<legend>Log In</legend>
<fieldset>
<label for="username">Username: </label>
<input id="username" type="text">
<label for="password">Password: </label>
<input id="password" type="password">
<button id="login" type="button">Log In!</button>
</fieldset>
</form>
纯 JavaScript 验证和重定向:
var users = [
{ username: 'user1', password: 'pass1' },
{ username: 'user2', password: 'pass2' },
{ username: 'user3', password: 'pass3' }
];
var button = document.getElementById('login');
button.onclick = function() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
for (var i = 0; i < users.length; i++) {
if(username == users[i].username && password == users[i].password) {
window.location.href = 'http://where/you/want/to/redirect/';
break;
}else{
alert('You are trying to break in!');
}
}
}
PS:这个例子只是向您展示了如何将 3 个用户存储在一个数组中,以及如何在前端验证输入,以便只有这些用户才能登录。