简体   繁体   中英

Button onclick event executing although button is not clicked [JavaScript]

I have a login page that validates and if the proper credentials are submitted then the user is redirected to another page, a session is created, and the login button is changed to logout on every page and an onclick event listener is added to it. The event listener clears the session.

For some reason when the user is successfully logged in and redirected, the session is created but if the page is refreshed or if user navigates to another page, the session is cleared without even clicking the logout button. Cannot seem to figure out why this is...

Here's the code:

<body>
    <!--Depending on sessions hide login and show logout / vice versa -->
    <div class="Header-nav-inner">
        <a id="login" href="/login" class="Header-nav-item Header-nav-item--active" data-test="template-nav">Login</a>
    </div>
    <form onsubmit="validate()">
        <h3>Email</h3><input type="email" id="email" /><br />
        <h3>Password</h3><input type="password" id="password" />
        <input type="submit" value="Login">
    </form>
</body>

<script>
    if (key[1] == document.getElementById('email').value
                        && key[2] == document.getElementById('password').value) {
                        alert('correct')
                        //Set session for email, name and date of birth
                        sessionStorage.setItem('email', key[1])
                        sessionStorage.setItem('name', key[3])
                        sessionStorage.setItem('dateOfBirth', key[4])
                        //window.location.replace("somewhere")
                    } else {
                        c += 1;
                        if (c == results.data.length) {
                            alert('Wrong username or password!')
                        }
                    }

    let sessionEmail = sessionStorage.getItem('email')
    let sessionName = sessionStorage.getItem('name')
    let sessionBirth = sessionStorage.getItem('dateOfBirth')

    var loginBtn = document.getElementById("login");
    if (sessionStorage.getItem('email') != null) {
        loginBtn.innerHTML = "LOGOUT";
        loginBtn.onclick = logout();
    } else {
        loginBtn.innerHTML = "LOGIN"
    }

    function logout() {
        sessionStorage.clear();
    }
</script>

Replace the following line

loginBtn.onclick = logout();

with

loginBtn.onclick = logout;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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