繁体   English   中英

如何防止 localStorage 保存相同的数据

[英]How to prevent localStorage from saving same data

我制作了一个任何人都可以登录的程序,但问题是即使它已经在 localStorage 中,它也会保存相同的名称。 当它在 localStorage 中已经具有相同的名称时,我希望它不会被保存

这是我的HTML5 & js代码

<!-- HTML5 -->
<div>
  <!-- login -->
  <form>
    <!-- UserName -->
    <input id="name" type="text" placeholder="Enter name">
    <br>
    <!-- password -->
    <input id="password" type="password" placeholder="Enter password">
    <br><br>
    <!-- login button -->
    <button id="saveButton">Log in</button>
    <br><br>
  </form>
  <script src="./saveName.js"></script>
  <script src="./savePassword.js"></script>
</div>
//JAVASCRIPT
function saveNames() {
  var newNames = document.getElementById('name').value;

  if (localStorage.getItem('id') == null) {
    localStorage.setItem('id', '[]');
  }

  var old_data = JSON.parse(localStorage.getItem('id'));

  old_data.push(newNames);

  localStorage.setItem('id', JSON.stringify(old_data));

  alert(localStorage.getItem('id'));
}

saveButton.addEventListener("click", function(e) {
  e.preventDefault();
  saveNames();
});
function saveNames() {
  var newNames = document.getElementById('name').value;

  if (localStorage.getItem('id') == null) {
    localStorage.setItem('id', '[]');
  }

  var old_data = JSON.parse(localStorage.getItem('id'));
  if (!old_data.includes(newNames)) {
  old_data.push(newNames);

  localStorage.setItem('id', JSON.stringify(old_data));
alert(localStorage.getItem('id'));
}
else return
}

saveButton.addEventListener("click", function(e) {
  e.preventDefault();
  saveNames();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM