首页 > 解决方案 > 未达到事件侦听器内部的 JS for 循环

问题描述

我正在构建一个简单的 html 表单并在登录按钮上单击我更新 url,但问题是未达到按钮事件侦听器内部的 for 循环。

    var user_credentials = {
        "andrea@gmail.com": "password",
        "hospitalagency@gmail.com": "hospitalagency",
        "user@gmail.com": "password"
    }

    const loginForm = document.getElementById("form");
    const loginButton = document.getElementById("login-form-submit");

    loginButton.addEventListener("click", (e) => {
        // e.preventDefault();
        const email = loginForm.email.value;
        const password = loginForm.password.value;
        
        for (let i = 0; i < user_credentials.length; i++) {
            if (Object.keys(user_credentials)[i] === email) {
                if(Object.values(user_credentials)[i] === password) {
                    console.log("hi");
                    window.location.pathname = "/html/home.html";
                }
            } else {
                window.location.reload();
            }
        }
    });

嗨永远不会“打印”,我不知道它是否是正确的词,但永远不会达到 for 循环。我试图在网上搜索如何调试,但我无法做到。loginForm 和 loginButton 不是问题,因为我尝试使用 console.log() 并且它们被很好地检测到。如果您对代码有任何更正,欢迎他们

标签: javascript

解决方案


user_credentials.length将始终未定义,因为它的对象,请尝试将其更改为 Array。


推荐阅读