解决单JS文件中多页面Firebase按钮addEventListener仅首个生效问题
问题解决方法
为什么合并后只有第一个按钮事件生效?
每个页面只存在对应功能的按钮,比如注册页面没有登录按钮,你直接调用LogIn.addEventListener时,LogIn这个元素不存在(会返回undefined),执行到这里会抛出错误,导致后续代码全部中断,所以只有第一个按钮的事件能绑定成功。
能不能用onclick实现?
可以,但不推荐。如果要做的话,需要把模块里的函数暴露到全局作用域:
- HTML里给按钮加
onclick属性:
<!-- 注册页按钮示例 --> <button id="signUp" onclick="handleSignUp()">注册</button>
- 在JS模块里把函数挂到
window上:
window.handleSignUp = function(e) { var fullname = document.getElementById('SignupName').value var email = document.getElementById('SignupEmail').value var password = document.getElementById('SignupPassword').value createUserWithEmailAndPassword(auth, email, password) .then((userCredential) => { const user = userCredential.user; set(ref(database, 'users/' + user.uid), { fullname: fullname, email: email }) alert('successful!!!') }) .catch((error) => { alert(error.message); }); }
这种方式耦合性高,不利于代码维护,更推荐用addEventListener的正确姿势。
单个JS文件绑定多页面按钮事件的正确方式
核心逻辑是:先获取元素,判断元素存在后再绑定事件,避免因元素不存在报错中断代码。修改后的代码如下:
// 注册按钮事件绑定 const signUpBtn = document.getElementById('signUp'); if (signUpBtn) { signUpBtn.addEventListener("click", (e) => { var fullname = document.getElementById('SignupName').value var email = document.getElementById('SignupEmail').value var password = document.getElementById('SignupPassword').value createUserWithEmailAndPassword(auth, email, password) .then((userCredential) => { const user = userCredential.user; set(ref(database, 'users/' + user.uid), { fullname: fullname, email: email }) alert('successful!!!') }) .catch((error) => { alert(error.message); }); }); } // 登录按钮事件绑定 const logInBtn = document.getElementById('LogIn'); if (logInBtn) { logInBtn.addEventListener("click", (e) => { var email = document.getElementById('LoginEmail').value var password = document.getElementById('LoginPassword').value signInWithEmailAndPassword(auth, email, password) .then((userCredential) => { alert("login!!!") window.location.href = "gamescard.html" }) .catch((error) => { alert(error.message); }); }); } // 登出按钮事件绑定(假设按钮ID为logOut) const logOutBtn = document.getElementById('logOut'); if (logOutBtn) { logOutBtn.addEventListener("click", (e) => { signOut(auth) .then(() => { alert("已登出") window.location.href = "login.html" }) .catch((error) => { alert(error.message); }); }); }
这样每个页面加载时,只会执行对应存在的按钮的事件绑定,不会因为元素不存在报错,所有按钮的事件都能正常生效。
内容的提问来源于stack exchange,提问作者Yeah aight
相关产品推荐
相关产品推荐

