JavaScript 如何使用户名创建表单在页面重新加载时保持隐藏不可见
问题描述
我正在编写一个用户名创建表单,该表单将在指定的容器中显示创建的用户名。我已经创建了表单和EventListener,可以在提交表单时触发。当提交表单时,会发生一个函数,使表单变为不可见并将项目设置为localstorage。它还在容器中显示所创建的用户名。(注意:我知道我在代码片段中编写的内容不起作用,但我在实际的html文件中进行了测试并且运行正常)。我想知道,如何使表单永久不可见(即使在页面重新加载时),如果用户名已存在,并且如何在页面重新加载时使用户名保留在h1容器中。非常感谢所有的帮助!
<!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>
解决方案
您可以修改您的代码,检查存储在 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>