简体   繁体   English

js文件中有多个addEventListeners,只有一个有效

[英]Multiple addEventListeners in js file, only one works

So I'm playing around with HTML and JS, and I have two web pages, each with their own addEventListener I need to work when a user submits a form from those pages.所以我在玩 HTML 和 JS,我有两个 web 页面,每个页面都有自己的 addEventListener 当用户从这些页面提交表单时我需要工作。 However, only the eventlistener for my Log In page is working - the one for my Reset Password page doesn't.但是,只有我的登录页面的事件监听器正在工作 - 我的重置密码页面的事件监听器没有。 I've tried swapping their order in the JS file, and then my Reset Password one works, and my Log In doesn't.我尝试在 JS 文件中交换他们的顺序,然后我的重置密码有效,而我的登录无效。 Is it possible to have many addEventListeners in one JS file all work appropriately when needed?是否可以在一个 JS 文件中让多个 addEventListener 在需要时都能正常工作?

Below is the code:下面是代码:

Log In In Page HTML:登录页面 HTML:

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log In</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.7/css/all.css">
</head>
<body id="formBodyBG">
<header>    
    <div>
        <div id="navMenu">
          <ul>
            <li class="logo">
                <a href="index.html" class="navLink home">Home</a>
            </li>
            <li class="createAccount">
              <a href="createAccount.html" class="navLink createAccountButton">Create Account</a>
            </li>
          </ul>
        </div>
      </div>
</header>
<section class="mainBody">
    <div class="leftSide"></div>
    <div class="mainForm">
            <h1 style="text-align:center; margin-bottom:12px; font-size:32px">Welcome Back!</h1>
            <h5 style="text-align:center; margin-bottom:25px">Log in to review, analyze past trends, or import new data.</h5>
            <form class="form" id="loginForm" action="dashboard.html" method="GET">
                <div class="mainFormDesign">
                    <label>Username</label>
                    <input type="text" id="username" name="username" class="input"><br>
                    <i class="fa fa-check-circle"></i>
                    <i class="fa fa-exclamation-circle"></i>
                    <small>Error message</small><br><br>
                </div>
                <div class="mainFormDesign">
                    <div style="width: 50%; float:left">
                        <label>Password</label>
                    </div>
                    <div style="width: 50%; float:right">
                        <label><a href="resetPassword.html" class="label">Forgot Password?</a></label>
                    </div>
                    <input id="password" type="password" name="password" class="input"><br>
                    <i class="fa fa-check-circle"></i>
                    <i class="fa fa-exclamation-circle"></i>
                    <small>Error message</small><br><br>
                </div>
                <button class="loginButton" id="loginSubmit">Log In</button>
                <br><br><hr>
                <h5 style="text-align:center; margin-bottom:35px;" class="secondCreateAccountLink">New to StigTracker? <a href="createAccount.html" class="accountLink">Create an account.</a></h5>
            </form>
    </div>
    <div class="rightSide"></div>
</section>
<script type="text/javascript" src="/pages/code.js"></script>

Reset Password Page HTML:重置密码页面 HTML:

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reset Password</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body id="formBodyBG">
<header>    
    <div>
        <div id="navMenu">
          <ul>
            <li class="logo">
                <a href="index.html" class="navLink home">Home</a>
            </li>
            <li class="createAccount">
              <a href="createAccount.html" class="navLink createAccountButton">Create Account</a>
            </li>
          </ul>
        </div>
      </div>
</header>
<section class="mainBody">
    <div class="leftSide"></div>
    <div class="mainForm">
        <h1 style="text-align:center; margin-bottom:12px; font-size:32px">Reset Your Password</h1>
        <h5 style="text-align:center; margin-bottom:25px">Enter a valid email to receive instructions on how to reset your password.</h5>
        <form class="form" id="resetForm" action="resetSuccess.html" method="GET">
            <div class="mainFormDesign">
                <label>Email</label>
                <input type="email" id="email" name="email" class="input"><br>
                <i class="fa fa-check-circle"></i>
                <i class="fa fa-exclamation-circle"></i>
                <small>Error message</small><br><br>
            </div>
            <button class="loginButton" id="resetSubmit">Reset Password</button>
        </form>
    </div>
    <div class="rightSide"></div>
</section>
<script type="text/javascript" src="/pages/code.js"></script>

JS: JS:

const username = document.getElementById('username')
const password = document.getElementById('password')
const email = document.getElementById('email')
const loginForm = document.getElementById('loginForm')
const resetForm = document.getElementById('resetForm')

loginForm.addEventListener('submit', (e) => {
    e.preventDefault()
    if (username.value === '' || username.value == null) {
        setErrorFor(username,'Username cannot be blank.')
    }
    else if (username.value !== 'testuser') {
        setErrorFor(username,'Username is not valid.')
    }
    else {
        setSuccessFor(username)
    }

    if (password.value === '' || password.value == null) {
        setErrorFor(password,'Password cannot be blank.')
    }
    else if (password.value !== '123456') {
        setErrorFor(password,'Password is not valid.')
    }
    else {
        setSuccessFor(password)
    }

    if (username.value === 'testuser' & password.value === '123456') {
        window.location.href = "index.html";
    }
})

resetForm.addEventListener('submit', (e) => {
    e.preventDefault()
    if (email.value === '' || email.value == null) {
        setErrorFor(email,'Email cannot be blank.')
    }
    else if (email.value !== 'edward.champa@us.af.mil') {
        setErrorFor(email,'Email is not valid.')
    }
    else {
        setSuccessFor(email)
    }

    if(!isEmail(email.value)) {
        setErrorFor(email,'Email is not valid.')
    }
    else {
        window.location.href = "index.html"; 
    }
})

function setErrorFor(input, message) {
    const mainFormDesign = input.parentElement;
    const small = mainFormDesign.querySelector('small');

    small.innerText = message;

    mainFormDesign.className = 'mainFormDesign error';
}

function setSuccessFor(input) {
    const mainFormDesign = input.parentElement;

    mainFormDesign.className = 'mainFormDesign success';
}

You will have an error on the resetform page since loginform doesn't exist, this stops the javascript from completing, the other way around it will probably throw an error, but work for the login part.. check the console indeed.. open the html in browser and press F12由于 loginform 不存在,您将在 resetform 页面上出现错误,这会阻止 javascript 完成,否则可能会引发错误,但适用于登录部分..确实检查控制台..打开html 在浏览器中按 F12

Solution: only add the eventlistener is the element !== null解决方法:只添加eventlistener就是元素!== null

if ((typeof loginForm === 'undefined') || (loginForm !== null)){
   loginForm.addEventListener......
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM