我一直在学习前端 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;
}
关于javascript - 如何更改 HTML 元素并重定向到另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69687158/