今天是第十九天我們可以寫一個javascript線上學習程式網頁程式管理系統,以下是我的程式碼
以下是這個簡單系統的檔案結構:
/online-learning-system
│
├── index.html    // 主頁面
├── login.html    // 登入頁面
├── register.html // 註冊頁面
├── dashboard.html // 學生儀表板
├── course.js     // 課程管理的JavaScript檔案
└── style.css     // 样式表
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Learning System</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>Welcome to the Online Learning System</h1>
        <nav>
            <ul>
                <li><a href="login.html">Login</a></li>
                <li><a href="register.html">Register</a></li>
            </ul>
        </nav>
    </header>
    <main>
        <section>
            <h2>Start Learning Today</h2>
            <p>Join now to access thousands of courses in different domains.</p>
            <a href="register.html" class="btn">Register Now</a>
        </section>
    </main>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Online Learning System</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>Login</h1>
    </header>
    <main>
        <form id="loginForm">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
            <button type="submit">Login</button>
        </form>
        <p>Don't have an account? <a href="register.html">Register here</a>.</p>
    </main>
    <script src="course.js"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - Online Learning System</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>Register</h1>
    </header>
    <main>
        <form id="registerForm">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
            <button type="submit">Register</button>
        </form>
        <p>Already have an account? <a href="login.html">Login here</a>.</p>
    </main>
    <script src="course.js"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Online Learning System</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>Welcome to your Dashboard</h1>
        <nav>
            <ul>
                <li><a href="courses.html">Browse Courses</a></li>
                <li><a href="my-courses.html">My Courses</a></li>
                <li><a href="index.html" id="logoutBtn">Logout</a></li>
            </ul>
        </nav>
    </header>
    <main>
        <section>
            <h2>Your Courses</h2>
            <div id="courseList"></div>
        </section>
    </main>
    <script src="course.js"></script>
</body>
</html>
// 假設的資料庫
let users = [];
let courses = [
    { id: 1, title: "JavaScript for Beginners", description: "Learn the basics of JavaScript" },
    { id: 2, title: "Advanced CSS", description: "Master the art of CSS" }
];
// 註冊處理
document.getElementById('registerForm')?.addEventListener('submit', function(event) {
    event.preventDefault();
    const name = document.getElementById('name').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    users.push({ name, email, password });
    alert('Registration successful! You can now login.');
    window.location.href = 'login.html';
});
// 登入處理
document.getElementById('loginForm')?.addEventListener('submit', function(event) {
    event.preventDefault();
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const user = users.find(user => user.email === email && user.password === password);
    
    if (user) {
        alert('Login successful!');
        localStorage.setItem('user', JSON.stringify(user));
        window.location.href = 'dashboard.html';
    } else {
        alert('Invalid email or password');
    }
});
// 顯示課程
window.onload = function() {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
        document.getElementById('courseList').innerHTML = courses.map(course => `
            <div class="course">
                <h3>${course.title}</h3>
                <p>${course.description}</p>
                <button onclick="enroll(${course.id})">Enroll</button>
            </div>
        `).join('');
    }
};
// 註冊課程
function enroll(courseId) {
    alert(`You have enrolled in course ID: ${courseId}`);
}
// 登出
document.getElementById('logoutBtn')?.addEventListener('click', function() {
    localStorage.removeItem('user');
});
body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
}
header {
    background-color: #4CAF50;
    color: white;
    padding: 1rem;
    text-align: center;
}
nav ul {
    list-style: none;
    padding: 0;
}
nav ul li {
    display: inline;
    margin: 0 1rem;
}
a {
    color: white;
    text-decoration: none;
}
main {
    margin: 2rem;
}
form {
    max-width: 300px;
    margin: auto;
    padding: 1rem;
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input {
    width: 100%;
    padding: 0.5rem;
    margin: 0.5rem 0;
}
button {
    width: 100%;
    padding: 0.7rem;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
}
.course {
    background-color: white;
    padding: 1rem;
    margin: 1rem 0;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
users 模擬用戶資料,當用戶註冊時,將其添加到 users 陣列中。登入時,檢查輸入的電子郵件和密碼是否與 users 陣列中的資料匹配。我會以javascript程式碼解釋為主
users 和 courseslet users = [];
let courses = [
    { id: 1, title: "JavaScript for Beginners", description: "Learn the basics of JavaScript" },
    { id: 2, title: "Advanced CSS", description: "Master the art of CSS" }
];
users:courses:courses 是一個包含課程物件的陣列。每個物件表示一個課程,並具有三個屬性:
id:課程的唯一識別碼。title:課程的名稱。description:課程的簡短描述。這是模擬的課程數據,未來你可能會從伺服器端動態載入這些課程。
document.getElementById('registerForm')?.addEventListener('submit', function(event) {
    event.preventDefault();
    const name = document.getElementById('name').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    users.push({ name, email, password });
    alert('Registration successful! You can now login.');
    window.location.href = 'login.html';
});
選擇註冊表單:document.getElementById('registerForm')
getElementById 函數來選取註冊表單。該表單在網頁中應該有 id="registerForm",這樣才會被成功選取。?. 是「可選鏈接運算符」(optional chaining operator),如果 registerForm 不存在,會避免報錯。事件監聽器:addEventListener('submit', function(event) {...})
addEventListener 為 registerForm 添加了一個監聽器,監聽當表單被提交時會觸發的 submit 事件。event.preventDefault():
提取表單數據:
document.getElementById('name').value、email 和 password 是從表單的輸入欄位中取得用戶輸入的數據。儲存用戶資料:
users.push({ name, email, password }):這裡將新註冊的用戶資訊(名稱、電子郵件和密碼)儲存為一個物件,並將這個物件推入 users 陣列中。顯示提示訊息並跳轉:
alert('Registration successful! You can now login.') 彈出一個對話框告訴用戶註冊成功。window.location.href = 'login.html':註冊成功後,頁面會跳轉到 login.html,即登入頁面。document.getElementById('loginForm')?.addEventListener('submit', function(event) {
    event.preventDefault();
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const user = users.find(user => user.email === email && user.password === password);
    
    if (user) {
        alert('Login successful!');
        localStorage.setItem('user', JSON.stringify(user));
        window.location.href = 'dashboard.html';
    } else {
        alert('Invalid email or password');
    }
});
選擇登入表單:
getElementById('loginForm') 來選取登入表單。事件監聽器:
submit 事件,執行該函數。防止表單默認行為:
event.preventDefault(),這樣表單提交時不會重新加載頁面。取得登入數據:
email 和 password 變數中。查找用戶:
users.find():這段代碼會在 users 陣列中查找是否有用戶的 email 和 password 與輸入的值匹配。如果找到符合條件的用戶,則該用戶會被儲存在 user 變數中。登入邏輯:
alert('Login successful!')),並且將這個用戶的資料存入瀏覽器的 localStorage 中,這樣登入狀態可以保持在後續頁面。最後會將頁面跳轉到使用者的主頁(如儀表板頁面 dashboard.html)。alert('Invalid email or password')),告知用戶帳號或密碼錯誤。window.onload = function() {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
        document.getElementById('courseList').innerHTML = courses.map(course => `
            <div class="course">
                <h3>${course.title}</h3>
                <p>${course.description}</p>
                <button onclick="enroll(${course.id})">Enroll</button>
            </div>
        `).join('');
    }
};
window.onload:
取得已登入用戶:
localStorage.getItem('user'):從 localStorage 中獲取之前登入成功後存儲的用戶資料。這是用來確認用戶是否仍處於登入狀態。JSON.parse():將取得的字串形式的用戶資料轉換回 JavaScript 的物件。顯示課程列表:
courses.map() 方法,將每一個課程物件轉換為對應的 HTML 標籤(包括課程名稱、描述和報名按鈕)。map():為每一個課程生成一段 HTML 字串,並使用 join('') 將所有課程組合成一個完整的 HTML 結構。這些 HTML 會被插入到頁面中的 courseList 區塊。function enroll(courseId) {
    alert(`You have enrolled in course ID: ${courseId}`);
}
enroll() 函數,並傳入課程的 id。資料發送到伺服器,並在後端記錄下用戶的註冊行為。
我們可以透過這個線上學習程式網頁程式管理系統來達成學生自學程式的目標。