iT邦幫忙

2025 iThome 鐵人賽

DAY 12
0
自我挑戰組

打造一個糖尿病自我監測小工具:從0開始學前端系列 第 12

Day12打造一個糖尿病自我監測小工具:從0開始學前端

  • 分享至 

  • xImage
  •  

昨天 script.js的部分有點搞錯了,今天修正+實作。

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";
});

report.html 頁面

我原本是直接先寫好一筆資料,但修改成從 localStorage 取資料。

  • const recordData = JSON.parse(localStorage.getItem("latestRecord")); 取資料
<!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>

成果展示

  • 填寫表單
    https://ithelp.ithome.com.tw/upload/images/20250912/20169698zuEc6Ddbxu.png
  • 轉跳至 report.html 結果呈現
    https://ithelp.ithome.com.tw/upload/images/20250912/20169698Bdg1JMIYc8.png

上一篇
Day11打造一個糖尿病自我監測小工具:從0開始學前端
下一篇
Day13打造一個糖尿病自我監測小工具:從0開始學前端
系列文
打造一個糖尿病自我監測小工具:從0開始學前端13
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言