如何使用户名创建表单即使在页面重新加载时也保持不可见?

How to make username creation form stay invisible even on page reload?

提问人:HTMLNerd_1 提问时间:10/21/2023 更新时间:10/21/2023 访问量:36

问:

所以我是 javascript 的初学者,我正在编写一个用户名创建表单,该表单在指定的容器中显示创建的用户名。我已经制作了表格,并且知道我何时提交表格。提交表单时发生的函数使表单不可见,并将项目设置为 。它还会在容器中显示创建的用户名。(注意:我知道我编码的内容在代码片段中不起作用,但我在实际的 html 文件中进行了测试并且它有效)。我想知道,如果用户名已经存在,如何使表单永远不可见(即使在页面重新加载时),以及如何使用户名在页面重新加载时留在 h1 容器中。感谢所有帮助!EventListenerlocalstorage

<!DOCTYPE html>
<html>

<body>
  <form id="username-creator" class="username-creator">
    <input type="text" id="username-creator-input" required>
    <button type="submit">Submit</button>
  </form>
  <div id="username-container">
    <h1 id="username-container-h1">
      <!-- This is where the created username goes -->
    </h1>
  </div>
  <script>
    document.getElementById('username-creator').addEventListener('submit', function(event) {
      event.preventDefault();
      var username = document.getElementById('username-creator-input').value;
      localStorage.setItem('username', username);
      document.getElementById('username-creator').style.display = "none";
      document.getElementById('username-container-h1').innerText = username;
    });
  </script>
</body>

</html>

JavaScript HTML 表单 本地存储 事件侦听器

评论


答:

2赞 XM01 - stands with Palestine 10/21/2023 #1

您可以修改代码以检查是否存在存储的用户名,并相应地调整表单的可见性。localstorage

这是更新代码:

<!DOCTYPE html>
<html>

<body>
  <form id="username-creator" class="username-creator">
    <input type="text" id="username-creator-input" required>
    <button type="submit">Submit</button>
  </form>
  <div id="username-container">
    <h1 id="username-container-h1">
      <!-- This is where the created username goes -->
    </h1>
  </div>
  <script>
   var storedUsername = localStorage.getItem('username');
   if (storedUsername) {
    document.getElementById('username-creator').style.display = "none";
    document.getElementById('username-container-h1').innerText = storedUsername;
                        }
    document.getElementById('username-creator').addEventListener('submit', function(event) {
      event.preventDefault();
      var username = document.getElementById('username-creator-input').value;
      localStorage.setItem('username', username);
      document.getElementById('username-creator').style.display = "none";
      document.getElementById('username-container-h1').innerText = username;
    });
  </script>
</body>

</html>