我决定使用Firebase而不是使用SQL和PHP,这使得后端开发更容易。但是,我得到了TypeError:无法读取ID元素的null错误属性'style':login_div。此代码大部分来自YouTube视频Firebase web login tutorial。当我尝试将注销按钮移出索引页面并转移到另一个HTML文件时,问题就出现了。我决定保留两者的副本,但是,如果行document.getElementById(“login_div”)。style.display =“block”,整个页面会不断刷新并在登录页面和我的主页之间来回切换。被更改或删除,我不知道如何解决这个问题。我尝试更改ID名称,它没有做任何事情,并尝试将div移动到主页,刚刚开始一遍又一遍地刷新整个页面。
firebase.auth().onAuthStateChanged(function(user) {
//checking with firebase if there is a user
if (user) {
// User is signed in successful
//document.getElementById("user_div").style.display = "block";
document.getElementById("login_div").style.display = "none";
var user = firebase.auth().currentUser;
if (user !== null) {
//what to display if user is logged in
window.location.href = "chat.html";
}
} else {
// No user logged in displays login div hides user div
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
function login() {
var userEmail = document.getElementById("email_field").value;
var userPassword = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Error messages for failed login
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
});
}
function logout() {
//log out function
firebase.auth().signOut().then(function() {
window.location.href = "index.html";
});
}
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<!-- login in page and button -->
<div id="login_div" class="main-div">
<h1>The Bridge Login</h1>
<input type="email" placeholder="Email..." id="email_field" />
<input type="password" placeholder="Password" id="password_field" />
<button onclick="login()">Log In</button>
</div>
<div id="user_div" class="loggedIn-div">
<button onclick="logout()">Logout</button>
</div>
<!-- firebase authentication server connection-->
<script src="https://www.gstatic.com/firebasejs/4.10.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
</script>
<script src="index.js"></script>
</body>
</html>