He estado aprendiendo desarrollo web front-end y pensé en desafiarme a mí mismo con un ejercicio, he creado un formulario HTML simple
<!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>y para JavaScript, esto es lo que estoy usando
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'; } })Lo que quiero aquí es que después de presionar enviar, la página web debería redirigir al .html de inicio de sesión que solo consiste en
<!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> Después de redirigir a login.html , también quiero que agregue la variable yourName de JavaScript a la etiqueta h1 , pero esto claramente no funciona.
agregue <script src="example.js"></script> a su archivo login.html y cambie example.js a
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; }