javascript Uncaught TypeError:Cannot read properties of null(阅读“addEventListener”)当我移动到另一个页面时发生[重复]

nkcskrwz  于 2024-01-05  发布在  Java
关注(0)|答案(1)|浏览(188)

此问题在此处已有答案

Why does jQuery or a DOM method such as getElementById not find the element?(7个答案)
2天前关闭。
在用户成功登录后,我想导航到不同的页面并导出auth,但是当我这样做时,我得到Uncaught TypeError:Cannot read properties of null(阅读'addEventListener')on the button,but when I remove the export auth and remove the import statement from profile.js I don't get the error. I'm only doing this for testing purposes.

index.html

<form>
            <div>
                <label for="email">Email:</label>
                <input type="text" name="email" id="email">
                <label for="password">Password:</label>
                <input type="password" name="password" id="password">
            </div>
        </form>
        <div>
            <button id="button">Login</button>
        </div>

字符串

index.js

// firebase configurations....

const auth = getAuth(app);
const button = document.getElementById("button");
function login() {
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;

signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
        const user = userCredential.user;
        // Handle successful login here
    })
    .catch((error) => {
        // Handle login error
        alert("Invalid login credentials");
    });
}
button.addEventListener("click", login);

onAuthStateChanged(auth, (user) => {
    if (user) {
        console.log("Signed In");

        // user is signed in
        const uid = user.uid;

        button.removeEventListener("click", login); // remove event lister
        // navigate to next page
        window.location.href = "/profile.html";

    } 
})

export { auth }

profile.js

import { auth } from "./index.js";

console.log(auth);

ntjbwcob

ntjbwcob1#

我假设你在head部分包含了你的脚本文件。如果这是正确的,那么你在调用下面的语句时犯了一个错误。

const button = document.getElementById("button");

字符串
在这个脚本被评估的时候,文档还没有完成加载,你应该等待它完成加载。window对象的load事件是文档完全加载的地方。

let button;
window.onload = function(){
    button = document.getElementById("button");
}

相关问题