首页 > 解决方案 > 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

标签: javascripthtml

解决方案


问题是您name在用户更新值并单击链接之前初始化值。

在处理程序中移动它,如下所示,以便您始终获得最新值:

  arrow.addEventListener("click", () => {
    localStorage.clear();
    localStorage.setItem("username", textBox.value);
  });

推荐阅读