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



我一直在学习前端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';
}
})

我想要的是在点击提交后,网页应该重定向到login .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;
}

相关内容

  • 没有找到相关文章

最新更新