【问题标题】:How to change HTML elements and redirect to another page如何更改 HTML 元素并重定向到另一个页面
【发布时间】:2021-10-23 10:15:33
【问题描述】:

我一直在学习前端 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 后,我还希望它从JavaScript 中将变量yourName 添加到h1 标记中,但这显然不起作用。

【问题讨论】:

  • 您可以使用method="get" 提交表单并从query parameters 读取用户名。但请记住:前端代码没有安全性。用户可以阅读const yourName = "John" const yourPass = "Doe"
  • 如果它是 GET 表单,则在表单处理 url CGI 脚本的末尾传递 NAME,但无论哪种方式,您还必须在表单标记中指定 action=。 w3schools.com/tags/att_form_method.asp
  • @SamuelMarchant 为什么你认为这是 CGI? login.html 是一个简单的 HTML 页面,而不是 CGI 脚本。
  • ...漫长的冬夜必须飞翔。

标签: javascript html css frontend


【解决方案1】:

&lt;script src="example.js"&gt;&lt;/script&gt; 添加到您的 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 2015-01-17
    • 2021-01-08
    • 1970-01-01
    • 2021-06-27
    相关资源
    最近更新 更多