const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");
const btnSignup = document.getElementById("btn-signup");
btnSignup.onclick = function () { // when mouse click "signup" button
const first_name = firstName.value; // getting the value of firstName and so on..
const last_name = lastName.value;
const e_mail = newEmail.value;
const pass_word = newPassword.value;
if (first_name && last_name && e_mail && pass_word) {
//set user input into JSON
let user_data = {
firstName: first_name,
lastName: last_name,
email: e_mail,
password: pass_word
}
//get to localstorage if there is existing user ||or make empty array[]
let clientsArr = JSON.parse(localStorage.getItem('users')) || [];
//ipush ang new user sa array
clientsArr.push(user_data);
//save to localstorage
localStorage.setItem('users', JSON.stringify(clientsArr));
}
// location.reload();
else if (user_data === localStorage.getItem('users')) { // THIS IS THE CODE THAT I AM TRYING
alert("User already existed");
}
};
我正在尝试在屏幕上显示错误消息或在浏览器上发出警告,此代码实际上有效,问题是如何识别本地存储中是否存在现有用户。我要说的是,如果内存中存在现有用户,则您的“登录”将不接受。谢谢!我对要运行的代码添加了注释。
答案 0 :(得分:1)
几点:
let
变量绑定到词法范围{}
。因此,user_data
在第二个else if
语句中将不可用。id
。在示例中,我将对象转换为字符串并进行比较。
// Fields
const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");
// Button
const btnSignup = document.getElementById("btn-signup");
function signUp() {
const first_name = firstName.value;
const last_name = lastName.value;
const e_mail = newEmail.value;
const pass_word = newPassword.value;
// If either of the values is empty
if (!first_name || !last_name || !e_mail || !pass_word) {
return;
}
//set user input into JSON
let user_data = {
firstName: first_name,
lastName: last_name,
email: e_mail,
password: pass_word
}
// convert to string
let user_data_str = JSON.stringify(user_data)
//get to localstorage if there is existing user ||or make empty array[]
let clientsArr = JSON.parse(localStorage.getItem('users')) || [];
// Convert to string
// Search the list if
const userExists = clientsArr.find(user => JSON.stringify(user) === user_data_str);
if (userExists) {
return alert('User already exists')
}
//ipush ang new user sa array
clientsArr.push(user_data);
//save to localstorage
localStorage.setItem('users', JSON.stringify(clientsArr));
}
// Attach listener
btnSignup.addEventListener('click', signUp);
<input id="firstName" />
<input id="lastName" />
<input id="newEmail" />
<input id="newPassword" />
<button id="btn-signup">Sign up</button>
答案 1 :(得分:0)
如果要在添加到localStorage中的“用户”之前尝试检查用户是否已经存在,则可以执行以下操作:
textView.attributedText = attributedPDFArticle