javascript - JavaScript localStorage,仅第二次检索值
问题描述
我正在尝试在此页面上检索用户的输入,然后将其显示为下一页上的标题,当用户单击箭头时加载该标题。当页面第一次加载时,您可以输入名称并单击下一步,但是会显示 No Hello 消息,但是如果您使用浏览器箭头返回,输入名称并提交正确的消息会显示。谢谢
<body>
<h1 class="message">Welcome</h1>
<form>
<div class="field-name">
<img src="/img/User.svg" alt="" class="userIcon" />
<input type="text" placeholder="Name" class="text_box" required />
<a href="/home/home.html" class="arrow inactive"
><img src="/img/arrow.svg" alt="" class="arrow_icon"/></a>
</div>
</form>
</body>
此页面的脚本:
const arrow = document.querySelector(".arrow");
const textBox = document.querySelector(".text_box");
const name = textBox.value;
window.addEventListener("load", () => {
textBox.addEventListener("input", () => {
arrow.classList.remove("inactive");
});
arrow.addEventListener("click", () => {
localStorage.clear();
localStorage.setItem("username", name);
});
});
应显示名称的页面的脚本:
const paragraph = document.querySelector(".text");
const UserName = localStorage.getItem("username");
window.addEventListener("load", () => {
paragraph.textContent = UserName;
});
如果我的解释不好会发生什么的视频:https ://ufile.io/yl37ir60
解决方案
问题是您name
在用户更新值并单击链接之前初始化值。
在处理程序中移动它,如下所示,以便您始终获得最新值:
arrow.addEventListener("click", () => {
localStorage.clear();
localStorage.setItem("username", textBox.value);
});
推荐阅读
- google-cloud-platform - 如何使用无服务器创建相同云功能的开发和生产实例?
- machine-learning - How can I get predictions from these pretrained models?
- c# - 获取 PrintDialog 子级的对话框句柄
- swift - 如何在CoreData中与Swift覆盖合并时防止多对关系NSManagedObject重复?
- bash - Using sed with a regex to replace strings
- javascript - 根据用户输入从表中删除行
- php - 如何使用 php 创建 pgp 密钥?
- android - 在扩展 Handler 的类中,handleMessage 返回的字符串出现奇怪的损坏
- c# - 如何拦截 Android 设备音量增大/减小按钮以在 Xamarin Forms 应用程序中打开相机?
- python - Why is heap slower than sort for K Closest Points to Origin?