<div class="container">
<h1>Firebase TodoList practice</h1>
<input type="text" id="memo" placeholder="請輸入待辦事項">
<button id="btn">送出</button>
<ul id="list"></ul>
</div>
.container {
margin: 0 auto;
width: 800px;
}
#memo {
width: 300px;
padding: 12px;
font-size: 16px;
border-radius: 6px;
border: 1px solid #666;
}
#btn {
padding: 12px 20px;
font-size: 14px;
background-color: green;
border: none;
color: #fff;
cursor: pointer;
border-radius: 6px;
transition: all 0.5s ease-in-out;
&:hover {
background: darken($color: green, $amount: 10%);
}
}
#list > li {
line-height: 1.8;
color: #333;
font-size: 18px;
&:hover {
font-weight: bold;
color: orangered;
cursor: pointer;
transition: all 0.6s;
}
}
View Compiled
const firebaseConfig = {
apiKey: "AIzaSyDhtziAvRJxhkVpSR8Lfb6JqZ1GE-jBfuY",
authDomain: "nodejsproject-d099d.firebaseapp.com",
projectId: "nodejsproject-d099d",
storageBucket: "nodejsproject-d099d.appspot.com",
messagingSenderId: "620886577949",
appId: "1:620886577949:web:bb7819e6cb71ffb05307f4",
measurementId: "G-CKJW9DEX9H",
};
firebase.initializeApp(firebaseConfig);
// DOM
let memo = document.querySelector("#memo");
const btn = document.querySelector("#btn");
const list = document.querySelector("#list");
// data
const todo = firebase.database().ref("todo");
// click
btn.addEventListener("click", function (e) {
console.log(memo.value); //確認取得 input 的值
//* 把 input 的值新增到 Firebase
todo.push({ content: memo.value });
});
// on
todo.on("value", function (snapshot) {
console.log(snapshot.val());
let str = "";
let data = snapshot.val();
for (let item in data) {
console.log(data[item]); //* 如果只取 item 會是資料庫的 key
str += `<li>${data[item].content}</li>`; //* 累加列表
}
console.log(str); // 確認取得 <li>xxxx</li> 的標籤
list.innerHTML = str;
memo.value = ""; //* 按下送出後,清空 input 的值
});
This Pen doesn't use any external CSS resources.