在JS函数中打开一个新的HTML页面,然后当之前的html是登录页面时在上面写一些HTML

问题描述 投票:0回答:2

嗨,我正在尝试创建一个登录页面,在您按下按钮后,它会转到索引。我这样做了,但现在我想更改部分 html 来表示欢迎回来(以及用户名)

到目前为止我已经写了这篇文章,但我不知道如何保存用户名,以便我可以在下一页中再次使用它。

这是 html:

<form id="login-form">
<!--Error Message-->
        <div id="login-error-msg-holder">
      <p id="login-error-msg">Invalid username <span id="error-msg-second-line">and/or password</span></p>
    </div>

<!--Form-->
    <div class="form-floating">
      <input type="name" class="form-control name " name="name" id="floatingInput" id="name-field" placeholder="user123">
      <label for="floatingInput">Username</label>
    </div>
    <div class="form-floating">
      <input type="password" id="password-field" class="form-control" id="floatingPassword" name="password" placeholder="Password">
      <label for="floatingPassword">Password</label>
    </div>

    <div class="form-check text-start my-3">
      <input class="form-check-input" type="checkbox" value="remember-me" id="flexCheckDefault">
      <label class="form-check-label" for="flexCheckDefault">
        Remember me
      </label>
    </div>
    <button class="btn w-100 py-2" id="login-form-submit" value="Login" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-body-secondary">&copy; 2017–2024</p>
  </form>
</main>

这是 js:

window.onload=loginButton.addEventListener("click",(e) => {
    e.preventDefault();
    const name = loginForm.name.value;
    const password = loginForm.password.value;

    if (name === "user123" && password === "1") {
        window.location.href = 'index.html';

    } else {
        loginErrorMsg.style.opacity = 1;
    }
})

function message(){

        if (window.history='Login.html' ) {
        document.getElementById('navlogin').innerHTML='Welcome back'+ name + '!';
        }
        
        else{
            document.getElementById('navlogin').innerHTML='';
        }
}

我尝试使用console.log,但我无法保存它一段时间,以便稍后使用。

有什么想法吗?

javascript html function console.log
2个回答
0
投票

使用会话存储来保存用户,这将允许您临时保存该值(它不会自行删除)并在页面重新启动时使用它而不会被删除。

sessionStorage.setItem("name",loginForm.name.value);

并访问该值:

const name = sessionStorage.getItem("name");

删除值:

sessionStorage.removeItem("name");

有关 sessionStorage 的更多信息


0
投票

我认为这是一个假认证。 在这种情况下,您可以只使用本地存储。 这显然不是一种安全的方法,也不适合生产代码。

当重定向到index.html时,您的页面会重新加载,导致JavaScript线程重新启动,从而导致所有变量丢失。 我还可以将您的代码包装如下

document.addEventListener("DOMContentLoaded", (event) => { /** your code here **/ });

© www.soinside.com 2019 - 2024. All rights reserved.