JavaScript 项目教程

JavaScript 是一种广泛使用的编程语言,它允许开发者创建动态和交互式网页。本教程将介绍如何创建一个基本的 JavaScript 项目。

项目介绍

在这个教程中,我们将创建一个简单的待办事项列表应用。这个应用将允许用户添加待办事项,并能够删除它们。

工具和资源

  • 文本编辑器:如 Visual Studio Code 或 Sublime Text
  • 网页浏览器:如 Google Chrome 或 Firefox
  • HTML:了解 HTML 基础
  • CSS:了解 CSS 基础

步骤

  1. 创建项目文件夹:在您的计算机上创建一个新的文件夹,命名为 javascript-project

  2. 创建 HTML 文件:在 javascript-project 文件夹中创建一个名为 index.html 的文件。

  3. 编写 HTML 代码:在 index.html 文件中,编写以下代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>待办事项列表</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>待办事项列表</h1>
    <form id="todo-form">
        <input type="text" id="todo-input" placeholder="添加待办事项">
        <button type="submit">添加</button>
    </form>
    <ul id="todo-list"></ul>
    <script src="script.js"></script>
</body>
</html>
  1. 创建 CSS 文件:在 javascript-project 文件夹中创建一个名为 styles.css 的文件。

  2. 编写 CSS 代码:在 styles.css 文件中,编写以下代码:

body {
    font-family: Arial, sans-serif;
    text-align: center;
}

h1 {
    color: #333;
}

#todo-form {
    margin-bottom: 20px;
}

#todo-input {
    margin-right: 10px;
}

#todo-list {
    list-style-type: none;
}

.todo-item {
    margin-bottom: 10px;
}
  1. 创建 JavaScript 文件:在 javascript-project 文件夹中创建一个名为 script.js 的文件。

  2. 编写 JavaScript 代码:在 script.js 文件中,编写以下代码:

document.getElementById('todo-form').addEventListener('submit', function(event) {
    event.preventDefault();
    const todoInput = document.getElementById('todo-input');
    const todoList = document.getElementById('todo-list');
    const todoItem = document.createElement('li');
    todoItem.textContent = todoInput.value;
    todoItem.classList.add('todo-item');
    todoList.appendChild(todoItem);
    todoInput.value = '';
});

扩展阅读

待办事项列表示例