在现代前端开发中,JavaScript起着至关重要的作用。我们将通过创建一个简单的书籍管理系统来深入探讨其基础。这个系统允许用户添加、编辑、删除书籍,并提供搜索功能。
1. 构建HTML结构
<div id="app">
<h2>书籍管理系统</h2>
<!-- 搜索部分 -->
<input type="text" id="search-input" placeholder="通过书名搜索...">
<button id="search-button">搜索</button>
<!-- 添加书籍部分 -->
<input type="text" id="book-title" placeholder="书名">
<input type="text" id="book-author" placeholder="作者">
<button id="add-button">添加书籍</button>
<!-- 书籍列表 -->
<table id="books-table">
<thead>
<tr>
<th>书名</th>
<th>作者</th>
<th>操作</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
此HTML结构为我们提供了搜索、添加和显示书籍的基本界面。
2. JavaScript逻辑
a) 初始化数据
我们使用一个数组books来存储书籍的数据。
let books = [];
b) 渲染书籍
renderBooks函数会遍历books数组,将书籍显示在表格中。
c) 添加和搜索书籍
我们为添加和搜索按钮分别绑定点击事件。
document.getElementById("add-button").addEventListener("click", function() {
/* ... 添加书籍逻辑 ... */
renderBooks();
});
document.getElementById("search-button").addEventListener("click", function() {
/* ... 搜索逻辑 ... */
renderBooks();
});
d) 编辑和删除书籍
/* ... 在 renderBooks 内部 ... */
const editButton = document.createElement("button");
editButton.textContent = "编辑";
editButton.addEventListener("click", function() {
/* ... 编辑逻辑 ... */
renderBooks();
});
const deleteButton = document.createElement("button");
deleteButton.textContent = "删除";
deleteButton.addEventListener("click", function() {
/* ... 删除逻辑 ... */
renderBooks();
});
这里的关键点是,在编辑或删除书籍后,我们需要重新渲染书籍列表,以确保显示的数据是最新的。
3. 总结
我们已经为书籍管理系统创建了基本的HTML结构,并通过JavaScript为其提供了主要功能。此系统虽简单,但覆盖了前端开发的许多核心概念,如DOM操作、事件处理和数据管理。