使用localStorage使注册/登录表单在HTML上工作时存在问题。作为作业的一部分,即使这些数据库或php更容易,我也无法使用它们。具体来说,问题是在我的提交功能期间发生的。
返回的语法错误是“标识符registerUser已被声明”,并在控制台中突出显示const reponse = processUser (username.value, password.value)
。
这是我的JavaScript代码:
//setup form
window.addEventListener("DOMContentLoaded", setupForm);
function setupForm() {
const form = document.getElementById("login");
form.addEventListener("submit", handleSubmit);
}
//handle Submit
function handleSubmit(event) {
event.preventDefault();
const {
Username,
Password,
login_type,
result
} = event.target;
const processUser = login_type.value == "register" ? registerUser : loginUser;
const response = processUser(username.value, password.value);
result.innerHTML = response;
}
//register new user
function registerUser(username, password) {
window.localStorage.setItem("username", username);
window.localStorage.setItem("password", password);
return 'New user ${username} now registered!';
}
//login existing user
function loginUser(username, password) {
const registeredUser = window.localStorage.getItem("username", username);
const registeredUser = window.localStorage.getItem("password", password);
const validUser = username == registeredUser;
const validPassword = password == registeredUser;
if (validUser && validPassword) {
return 'User ${username} successfully logged-in!';
}
//error form for incorrect username or password
else if (!validUser) return 'Incorrect username or password';
}
HTML表单:
<fieldset>
<form id="login" action="submit" method="post">
<legend><b>Login here!</b></legend><br />
<div>
<label for="username">Username:</label>
<input id="username" type="text" name="username" required />
</div>
<div>
<label for="password">Password:</label>
<input id="password" type="password" name="Password" required />
</div>
</fieldset>
<span>
<input id="login" type="hidden" name="login_type" value="login" checked="checked"></input>
<!--Hidden for the purposes of my script working-->
<input type="submit" value="Submit" /><br /><br />
<output name="result"></output>
</fieldset>
</span>
任何帮助将不胜感激,因为这非常令人沮丧!
答案 0 :(得分:2)
2个变量的名称已经registeredUser
。
const registeredUser = window.localStorage.getItem("username",
username);
const registeredUser = window.localStorage.getItem("password",
password);
所以我没有尝试使用registeredUser
,而是将其更改为registeredPassword
//login existing user
function loginUser(username, password){
const registeredUser = window.localStorage.getItem("username",
username);
const registeredPassword = window.localStorage.getItem("password",
password);
const validUser = username === registeredUser;
const validPassword = password === registeredPassword;
也使用===
代替==
reasons why
答案 1 :(得分:0)
您两次声明了标识符:
const registeredUser = window.localStorage.getItem("username",
username);
const registeredUser = window.localStorage.getItem("password",
password);