3 回答
![?](http://img1.sycdn.imooc.com/533e4c1500010baf02200220-100-100.jpg)
TA贡献1735条经验 获得超5个赞
您需要更改以下几行。您正在使用对象,但不是输入的值。您需要引用对象的 value 属性才能获得实际输入。
var idInput = document.getElementById("id").value; var pwInput = document.getElementById("pw").value;
![?](http://img1.sycdn.imooc.com/533e4c9c0001975102200220-100-100.jpg)
TA贡献1826条经验 获得超6个赞
写这个 if 的更好方法是
if(idInput == username[0] && pwInput == password[0]){
}
else if(idInput == username[1] && pwInput == password[1]{
}
else if(idInput == username[2] && pwInput == password[2]{
}
else {
alert(“User or password wrong.”);
}
如果您有可变数量的用户,则可以执行循环:
function loginCheck(username, password, idInput, pwInput){
for(i = 0; i < username.length; i++){
if(username[i] == idInput && password[i] == pwInput)
return 1;
}
return 0;
}
现在是一个安全问题:永远不要在客户端进行此检查。不良用户可以尝试阅读您的代码并获得访问权限。更好的方法是在将加密数据发送到 Web 服务器检查(例如 PHP)之前,使用哈希(推荐 SHA 256)对 idInput 和 pwInput 进行加密。因此,您可以防止不良用户访问,并且您的用户可以防止密码泄露。
![?](http://img1.sycdn.imooc.com/5458478b0001f01502200220-100-100.jpg)
TA贡献1789条经验 获得超8个赞
首先,您试图评估元素而不是它们的价值。此外,您还有很多不必要的条件。我们还想重组我们存储登录凭据的方式,使其更直观。
function login() {
// Instead of storing usernames and passwords in separate arrays,
// we instead will store them as an array of objects with username
// and password properties
var logins = [
{ username: 'user1', password: '1' },
{ username: 'user2', password: '2' },
{ username: 'user3', password: '3' }
];
// Get the values of our inputs
var idInput = document.getElementById("id").value;
var pwInput = document.getElementById("pw").value;
// The find method on array returns the first occurrence in the
// array if the condition evaluates to true. In this case, we
// need to make sure the username and password match what was
// entered. The !== undefined determines whether or not find
// returned a match that met the search criteria.
const success = logins.find(login => login.username == idInput && login.password == pwInput) !== undefined;
// If it found a match, then we alert the appropriate response.
if(success) {
alert('Successful login!');
} else {
alert('Failed login!');
}
}
<table>
<tr>
<td>Login Id:</td>
<th>
<INPUT type="text" Size="40" Maxlength="35" id="id" placeholder="Your Username Here">
</th>
</tr>
<tr>
<td>Password:</td>
<th>
<INPUT type="text" Size="40" Maxlength="40" id="pw" placeholder="Your Password Here">
</th>
</tr>
</table>
<button onclick="login()">Login</button>
添加回答
举报