如何更改 HTML 元素并重定向到另一个页面

How to change HTML elements and redirect to another page

我一直在学习前端 Web 开发并想通过练习来挑战自己,我创建了一个简单的 HTML 表单

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
    <form id="form">
        <label for="name">Name:</label><br>
        <input type="text" id="name"><br>
        <label for="pass">Password:</label><br>
        <input type="password" id="pass"><br><br>
        <input type="submit" value="Submit">
      </form> 

<script src="example.js"></script>
</body>
</html>

对于 JavaScript,这就是我正在使用的

const form = document.getElementById('form')
const formName = document.getElementById('name')
const formPass = document.getElementById('pass')

const yourName = "John"
const yourPass = "Doe"

form.addEventListener('submit', function(e){
    e.preventDefault()
    if (formName.value == yourName && formPass.value == yourPass) {
    document.querySelector('loginName').innerHTML = yourName;
    window.location.href = 'login.html';
    }
})

我在这里想要的是点击提交后,网页应该重定向到登录 .html,它只包含

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 id="loginName"></h1>
</body>
</html>

重定向到 login.html 后,我还希望它将变量 yourName 从 JavaScript 添加到 h1 标记,但这显然不起作用。

<script src="example.js"></script> 添加到您的 login.html 文件并将 example.js 更改为

const formName = document.getElementById('name')
const formPass = document.getElementById('pass')

const yourName = "John"
const yourPass = "Doe"

if(document.URL.indexOf('example.html') != -1){
    form.addEventListener('submit', function(e){
        e.preventDefault()
        if (formName.value == yourName && formPass.value == yourPass) {
            window.location.href = 'login.html';
        }
    })
}

if(document.URL.indexOf('login.html') != -1){
    document.getElementById('loginName').innerHTML = yourName;
}