iT邦幫忙

2024 iThome 鐵人賽

DAY 16
0
JavaScript

Javascript網頁程式管理系統系列 第 16

day 16 javascript線上圖書館網頁程式管理系統

  • 分享至 

  • xImage
  •  

今天是第十六天我們可以寫一個javascript線上圖書館網頁程式管理系統,以下是我的程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Library Management System</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        .book-list {
            margin-top: 20px;
        }
        .book-list table {
            width: 100%;
            border-collapse: collapse;
        }
        .book-list table, .book-list th, .book-list td {
            border: 1px solid #ddd;
        }
        .book-list th, .book-list td {
            padding: 10px;
            text-align: left;
        }
        .book-list th {
            background-color: #f2f2f2;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            margin-right: 10px;
        }
        input[type="text"] {
            padding: 5px;
            width: 300px;
        }
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>

    <h1>Online Library Management System</h1>
    
    <div>
        <h2>Add a New Book</h2>
        <div class="form-group">
            <label for="bookTitle">Title:</label>
            <input type="text" id="bookTitle" placeholder="Enter book title">
        </div>
        <div class="form-group">
            <label for="bookAuthor">Author:</label>
            <input type="text" id="bookAuthor" placeholder="Enter book author">
        </div>
        <button onclick="addBook()">Add Book</button>
    </div>
    
    <div class="book-list">
        <h2>Book List</h2>
        <table>
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Author</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody id="bookTableBody">
                <!-- Book list will be appended here -->
            </tbody>
        </table>
    </div>

    <script>
        let books = [];

        function addBook() {
            const title = document.getElementById('bookTitle').value;
            const author = document.getElementById('bookAuthor').value;
            
            if (title === '' || author === '') {
                alert('Please fill in both fields.');
                return;
            }
            
            const book = {
                title: title,
                author: author
            };
            
            books.push(book);
            displayBooks();
            
            document.getElementById('bookTitle').value = '';
            document.getElementById('bookAuthor').value = '';
        }

        function displayBooks() {
            const tableBody = document.getElementById('bookTableBody');
            tableBody.innerHTML = ''; // Clear previous data
            
            books.forEach((book, index) => {
                const row = `
                    <tr>
                        <td>${book.title}</td>
                        <td>${book.author}</td>
                        <td><button onclick="removeBook(${index})">Delete</button></td>
                    </tr>
                `;
                tableBody.innerHTML += row;
            });
        }

        function removeBook(index) {
            books.splice(index, 1);
            displayBooks();
        }
    </script>

</body>
</html>

我會以javascript作程式碼講解

1. 變數宣告

let books = [];

這行宣告了一個空的陣列 books,用來儲存書籍資料。每次新增一本書時,會把書籍的標題和作者存入這個陣列中。這是一個全域變數,所以可以在其他函數中使用。


2. addBook() 函數

function addBook() {
    const title = document.getElementById('bookTitle').value;
    const author = document.getElementById('bookAuthor').value;
    
    if (title === '' || author === '') {
        alert('Please fill in both fields.');
        return;
    }
    
    const book = {
        title: title,
        author: author
    };
    
    books.push(book);
    displayBooks();
    
    document.getElementById('bookTitle').value = '';
    document.getElementById('bookAuthor').value = '';
}

功能:

這個函數處理使用者新增書籍的操作,步驟如下:

  1. 取得輸入值

    • 使用 document.getElementById('bookTitle').valuedocument.getElementById('bookAuthor').value 分別取得輸入框中的書名和作者名稱。
  2. 檢查空白輸入

    • 如果書名或作者名稱沒有輸入 (title === '' || author === ''),會跳出一個提示視窗 alert('Please fill in both fields.'),要求使用者必須輸入這兩個欄位的資料,然後使用 return 終止函數執行。
  3. 建立書籍物件

    • 將輸入的書名和作者名稱存入一個物件 book 中:
      const book = {
          title: title,
          author: author
      };
      
      這個物件會有兩個屬性:titleauthor
  4. 加入書籍到陣列

    • 使用 books.push(book) 將書籍物件新增到 books 陣列中。
  5. 顯示書籍

    • 呼叫 displayBooks() 函數來更新並顯示書籍列表,確保新加入的書會顯示在表格中。
  6. 清空輸入框

    • 當書籍新增成功後,將書名和作者的輸入框清空:
      document.getElementById('bookTitle').value = '';
      document.getElementById('bookAuthor').value = '';
      

3. displayBooks() 函數

function displayBooks() {
    const tableBody = document.getElementById('bookTableBody');
    tableBody.innerHTML = ''; // Clear previous data
    
    books.forEach((book, index) => {
        const row = `
            <tr>
                <td>${book.title}</td>
                <td>${book.author}</td>
                <td><button onclick="removeBook(${index})">Delete</button></td>
            </tr>
        `;
        tableBody.innerHTML += row;
    });
}

功能:

此函數負責將書籍列表顯示在表格中,步驟如下:

  1. 取得表格的 tbody

    • 使用 document.getElementById('bookTableBody') 取得表格的 <tbody> 元素,這是要將書籍顯示的地方。
  2. 清空表格內容

    • 使用 tableBody.innerHTML = ''; 清空 tbody 內部的 HTML,避免重複顯示書籍資料。
  3. 遍歷 books 陣列

    • 使用 books.forEach() 方法遍歷每一本書。forEach() 會依次對 books 陣列中的每一個書籍物件進行操作。book 代表當前書籍,index 代表書籍在陣列中的索引。
  4. 動態生成表格行

    • 透過模板字串 (Template Literal) ${},將每一本書的 titleauthor 放入表格中:
      const row = `
          <tr>
              <td>${book.title}</td>
              <td>${book.author}</td>
              <td><button onclick="removeBook(${index})">Delete</button></td>
          </tr>
      `;
      
    • 在這裡,每本書會產生一個表格 <tr> 行,並加入一個 "Delete" 按鈕,當按下此按鈕時會呼叫 removeBook() 函數並傳遞對應的 index 作為參數。
  5. 將行加入表格

    • 使用 tableBody.innerHTML += row; 將生成的每一行書籍資料新增到表格中,更新顯示。

4. removeBook() 函數

function removeBook(index) {
    books.splice(index, 1);
    displayBooks();
}

功能:

此函數負責刪除書籍,步驟如下:

  1. 從陣列中刪除書籍

    • splice() 方法用來從 books 陣列中刪除指定的書籍。傳遞的參數 index 是書籍在陣列中的位置,1 代表刪除一個元素:
      books.splice(index, 1);
      
  2. 更新書籍列表

    • 呼叫 displayBooks() 函數,重新顯示刪除書籍後的書籍列表。

總結

  • books 陣列:用來儲存所有書籍的資料。
  • addBook():將使用者輸入的書名和作者新增到 books 陣列中,並更新顯示。
  • displayBooks():更新並顯示書籍列表,動態生成 HTML 表格。
  • removeBook():從 books 陣列中刪除指定書籍,並更新顯示。

上一篇
day 15 javascript餐廳推薦網頁程式管理系統
下一篇
day 17 javascript自動優化規劃行程系統
系列文
Javascript網頁程式管理系統25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言