我如何解决本地存储和JavaScript的问题

时间:2018-04-06 00:07:27

标签: javascript html css

我创建了一个注册相关功能,以便在注册时保存用户数据。我似乎没有得到问题,但数据没有保存到本地存储。我应该工作得很好,但我无法弄清问题是什么。

javascript文件执行以下操作 1)处理有人通过电子邮件复制数据的情况 2)将对象保存到传递给数组的本地存储

var signUpBtn = document.querySelector('#signUp');
var signUpOver = document.querySelector('.signup__overlay');

var signInBtn = document.querySelector('#signIn');
var signInOver = document.querySelector('.signin__overlay');

var fullname = document.querySelector('#name');
var email = document.querySelector('#email');
var password = document.querySelector('#password');
var age = document.querySelector('#age');
var occupation = document.querySelector('#occupation');
var Address = document.querySelector('#address');

var signupSubmitClicked = document.querySelector('#signupClicked'); 

signupSubmitClicked.addEventListener('click', () => {
  if (fullname.value=="" || email.value=="" || password.value=="" || age.value=="" || occupation.value=="" || Address.value=="") {
    alert("incomplete datails, please fill up everything")
  } else {
    alert("item created")
    addUser(fullname, email, password, age,  occupation, Address);
  }
});

var fetchUsers = () => {
  try {
      var userString = localStorage.getItem('userData');
      return JSON.parse(userString);            
  } catch (error) {
      return [];
  }
};

var saveUser = (users) => {
  localStorage.setItem('userData', JSON.stringify(users));
};

var addUser = (fullname, email, password, age,  occupation, Address) => {
  var users = fetchUsers();
  var user = {
      fullname,
      email,
      password,
      age,
      occupation,
      Address
  };

  var duplicateUsers = users.filter(user => user.email === email);

  if (duplicateUsers.length === 0) {
      users.push(user);
      saveUser(users);
      return user;
  }
};

/*************
signup popup
*************/
signUpBtn.addEventListener('click', () => {
  signUpOver.style.display = 'block';
});

signUpOver.addEventListener('click', () => {
  if(event.target == signUpOver){
    signUpOver.style.display = "none";
  }
});
/*************
signup popup
*************/

/*************
signin popup
*************/
signInBtn.addEventListener('click', () => {
  signInOver.style.display = 'block';
});

signInOver.addEventListener('click', () => {
  if(event.target == signInOver){
    signInOver.style.display = "none";
  }
});
/*************
signin popup
*************/
/** the end */
body {
  width: 100%;
  margin: 0;
  background-color: #F8F9F9;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  align-content: center;
}

#mainPage,
#userPage {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  align-content: center;
}

#userPage {
  display: none;
}

/********************
overlay
********************/
.signup__overlay {
  position: fixed;
  display: none;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background-color: rgba(0,0,0,0.8);
  z-index: 1;
}

.signup__content{
  position: relative;
  width: 100%;
  max-width: 520px;
  background-color: #ffffff;
  opacity: 1;
  margin: 64px auto;
  padding: 20px;
}

.signin__overlay {
  position: fixed;
  display: none;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background-color: rgba(0,0,0,0.8);
  z-index: 1;
}

.signin__content{
  position: relative;
  width: 100%;
  max-width: 520px;
  background-color: #ffffff;
  opacity: 1;
  margin: 64px auto;
  padding: 20px;
}


/********************
overlay ending
********************/

.headerMain {
  background-color: #000;
  color: #fff;
  width: 100%;
  margin-bottom: 50px;
  height: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  align-content: center;
  justify-content: flex-start;
}

.headerUser {
  background-color: #000;
  color: #fff;
  width: 100%;
  margin-bottom: 50px;
  height: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  align-content: center;
  justify-content: flex-start;
}

.upButton {
  margin-bottom: 20px;
}

.upButton, .inButton {
  padding-top: 15px;
  padding-bottom: 15px;
  cursor: pointer;
  width: 100%;
  max-width: 200px;
  background-color: #239B56;
  border: #239B56;
  color: snow;
}

label {
  padding-top: 20px;
}

label,
input {
  width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>User system</title>
  <link rel="stylesheet" href="css/index.css">
</head>
<body>

  <div id="mainPage">

      <div class="signup__overlay">
        <div class="signup__content">
          <form>
            <label for="name">Full Name</label>
            <input required type="text" id="name" name="name">

            <label for="email">Email</label>
            <input required type="text" id="email" name="email">

            <label for="password">Password</label>
            <input required type="password" id="password" name="password">

            <label for="age">Age</label>
            <input required type="text" id="age" name="age">

            <label for="occupation">Occupation</label>
            <input required type="text" id="occupation" name="occupation">

            <label for="address">Address</label>
            <input required type="text" id="address" name="address">

            <input type="submit" id="signupClicked">
          </form>
        </div>
      </div>

      <div class="signin__overlay">
        <div class="signin__content">
          <form>
            <label for="email">Email</label>
            <input required type="text" id="Email" name="email">

            <label for="email">Password</label>
            <input required type="Password" id="Password" name="Password">

            <input type="submit" id="signinClicked">
          </form>
        </div>
      </div>


    <header class="headerMain">User System</header>
    <section>
        <button class="upButton" id="signUp">Sign Up</button>

        <button class="inButton" id="signIn">Sign In</button>
    </section>

  </div>

  <div id="userPage">

      <header class="headerUser">User System</header>
      <section>
          
      </section>
  
    </div>
    
    <script src="js/index.js"></script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

LocalStorage条目在返回null的开头为空时,您不会处理此案例。 JSON.parse(null);仅为null,因此fetchUsers会返回null,但您会继续

var users = fetchUsers();
// …
var duplicateUsers = users.filter(user => user.email === email);

如果您打开browser console (dev tools)(点击 F12 )并读取此错误,则应该生成TypeError: users is null

相反,默认为[],如下所示:

var fetchUsers = () => {
  try {
      var userString = localStorage.getItem('userData');
      return JSON.parse(userString) || [];
  } catch (error) {
      return [];
  }
};

其他事项:

  • 作为pointed out by epascarello,您应该在表单未完全填写时阻止提交。您可能希望无条件地阻止默认值,并根据您的需要以编程方式提交表单:
signupSubmitClicked.addEventListener('click', (e) => {
  if (fullname.value=="" || email.value=="" || password.value=="" || age.value=="" || occupation.value=="" || Address.value=="") {
    alert("incomplete datails, please fill up everything");
    e.preventDefault();
  } else {
    alert("item created");
    addUser(fullname, email, password, age, occupation, Address);
  }
});

答案 1 :(得分:-3)

请参阅MDN文档Window.localStorage。请注意,在将任何对象存储到带有JSON.stringify的localstorage之前,必须对其进行strinigify,然后在读取它们时可以将它们解析回对象。

  

localStorage.setItem(&#39; myCat&#39;,&#39; Tom&#39;);