昨天 script.js的部分有點搞錯了,今天修正+實作。
流程:取得表單資料 → 存入localStorage
→ 轉跳至 report.html 頁面
document.getElementById("recordForm").addEventListener("submit", function(event) {
event.preventDefault(); // 阻止表單真的送出
// 取得表單資料
const record = {
date: document.getElementById("date").value,
weight: document.getElementById("weight").value,
exercise: document.querySelector('input[name="exercise"]:checked').value,
exercise_detail: document.getElementById("exercise_detail").value,
medication: document.querySelector('input[name="medication"]:checked').value,
medication_detail: document.getElementById("medication_detail").value,
bf_glucose: document.getElementById("bf_glucose").value,
af_glucose: document.getElementById("af_glucose").value,
remark: document.getElementById("remark").value
};
// 存到 localStorage(先轉成 JSON)
localStorage.setItem("latestRecord", JSON.stringify(record));
// 跳轉到報告頁
window.location.href = "report.html";
});
我原本是直接先寫好一筆資料,但修改成從 localStorage 取資料。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>紀錄報告</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>最新紀錄</h1>
<div id="report"></div>
<script>
// 從 localStorage 取資料
const recordData = JSON.parse(localStorage.getItem("latestRecord"));
if (recordData) {
document.getElementById("report").innerHTML = `
<p><strong>日期:</strong> ${recordData.date}</p>
<p><strong>體重:</strong> ${recordData.weight} kg</p>
<p><strong>運動狀況:</strong> ${recordData.exercise} ${recordData.exercise === "yes" ? `(${recordData.exercise_detail})` : ""}</p>
<p><strong>藥物使用:</strong> ${recordData.medication} ${recordData.medication === "yes" ? `(${recordData.medication_detail})` : ""}</p>
<p><strong>餐前血糖:</strong> ${recordData.bf_glucose}</p>
<p><strong>餐後血糖:</strong> ${recordData.af_glucose}</p>
<p><strong>備註:</strong> ${recordData.remark}</p>
`;
} else {
document.getElementById("report").innerHTML = `<p>目前沒有紀錄。</p>`;
}
</script>
</body>
</html>