【发布时间】:2022-01-10 14:48:26
【问题描述】:
美好的一天, 这是我正在尝试制作的某种日记,localStorage setItem 部分很好,这是我遇到问题的 getItem,在将条目添加到表后,当我刷新时,所有条目都消失了我只剩下 1 行带有默认输入值(“state?”和“”)。
JS代码:
const state = document.querySelector("#state");
const why = document.querySelector(".why");
const button = document.querySelector(".button");
const table = document.querySelector(".table");
// Date
var currentDate = new Date();
let cDay = currentDate.getDate();
let cMonth = currentDate.getMonth() + 1;
let cYear = currentDate.getFullYear();
let cDate = cMonth + "-" + cDay;
var sArray = [];
// Check if there's data in local storage
if (localStorage.getItem("states")) {
sArray = JSON.parse(localStorage.getItem("states"));
}
getDataFromLocalStorage();
button.addEventListener("click", () => {
if (state.value !== "state?") {
addToArray();
why.value = "";
state.value = "state?";
}
});
function addToArray() {
addToTable();
addDataToLocalStorage();
}
function addDataToLocalStorage() {
window.localStorage.setItem("states", JSON.stringify(sArray));
}
function addToTable() {
// Object
let dataObject = {
state: state.value,
reason: why.value,
};
// Add to array
sArray.push(dataObject);
const tr = document.createElement("tr");
const tdstate = document.createElement("td");
const tdWhy = document.createElement("td");
const tdDate = document.createElement("td");
tr.appendChild(tdstate);
tr.appendChild(tdWhy);
tr.appendChild(tdDate);
table.appendChild(tr);
tdstate.innerText = dataObject.state;
tdWhy.innerText = dataObject.reason;
tdDate.innerText = cDate;
}
function getDataFromLocalStorage() {
let data = window.localStorage.getItem("states");
if (data) {
let states = JSON.parse(data);
addToTable(states);
}
}
这是 HTML 代码
<body>
<h1>How are you feeling today?</h1>
<div class="content">
<div class="form">
<select name="state" id="state">
<option>State?</option>
<option value="very happy">Very happy</option>
<option value="happy">Happy</option>
<option value="okay">Okay</option>
<option value="sad">Sad</option>
<option value="terrible">Terrible</option>
</select>
<input class="why" type="text" placeholder="Why?" />
<input class="button" type="button" value="Add" />
</div>
<table class="table">
<th>State</th>
<th>Reason</th>
<th>Date</th>
</table>
</div>
<script src="script.js"></script>
</body>
【问题讨论】:
标签: javascript html local-storage