项目实例分析 | 青训营

88 阅读2分钟

任务管理应用程序

创建一个简单的任务管理应用程序,用户可以添加、编辑和删除任务。

HTML

<!DOCTYPE html>
<html>
<head>
  <title>任务管理应用程序</title>
</head>
<body>
  <h1>任务清单</h1>
  <input type="text" id="taskInput" placeholder="添加新任务">
  <button onclick="addTask()">添加</button>
  <ul id="taskList"></ul>

  <script src="script.js"></script>
</body>
</html>

JavaScript

const taskInput = document.getElementById('taskInput');
const taskList = document.getElementById('taskList');

function addTask() {
  const taskText = taskInput.value;
  if (taskText.trim() === '') {
    return;
  }

  const taskItem = document.createElement('li');
  taskItem.textContent = taskText;
  taskItem.addEventListener('click', editTask);
  taskList.appendChild(taskItem);

  taskInput.value = '';
}

function editTask(event) {
  const taskItem = event.target;
  const newText = prompt('编辑任务', taskItem.textContent);
  if (newText !== null) {
    taskItem.textContent = newText;
  }
}

taskInput.addEventListener('keydown', function (event) {
  if (event.key === 'Enter') {
    addTask();
  }
});


任务清单.png

功能和解决的问题: 这个应用程序实现了一个简单的任务管理系统,用户可以在输入框中输入任务,点击"添加"按钮或按下回车键来添加任务。任务被添加到一个无序列表中,用户可以单击任务以编辑其内容。通过这个项目,你可以学习如何处理用户输入、创建和操纵DOM元素,以及使用事件监听器来处理用户交互。

天气预报应用程序

使用天气API获取实时天气数据,并在网页上展示给用户。

HTML

<!DOCTYPE html>
<html>
<head>
  <title>天气预报应用程序</title>
</head>
<body>
  <h1>实时天气预报</h1>
  <input type="text" id="cityInput" placeholder="输入城市">
  <button onclick="getWeather()">获取天气</button>
  <div id="weatherInfo"></div>

  <script src="script.js"></script>
</body>
</html>

JavaScript

const cityInput = document.getElementById('cityInput');
const weatherInfo = document.getElementById('weatherInfo');
const apiKey = 'YOUR_API_KEY'; // 你需要替换成你自己的 API Key

async function getWeather() {
  const city = cityInput.value;
  if (city.trim() === '') {
    return;
  }

  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
  
  try {
    const response = await fetch(apiUrl);
    const data = await response.json();
    
    if (data.cod === 200) {
      const weatherDescription = data.weather[0].description;
      const temperature = data.main.temp;
      
      weatherInfo.innerHTML = `
        <p>城市:${city}</p>
        <p>天气:${weatherDescription}</p>
        <p>温度:${temperature}°C</p>
      `;
    } else {
      weatherInfo.innerHTML = '无法获取天气信息';
    }
  } catch (error) {
    console.error('获取天气数据时出错:', error);
  }
}

功能和解决的问题: 这个应用程序使用了一个天气API来获取指定城市的实时天气数据,然后将城市名称、天气描述和温度显示在网页上。通过这个项目,你可以学习如何使用异步操作获取数据,处理API响应,以及如何在网页上呈现数据。记得将 YOUR_API_KEY 替换成你自己的 OpenWeatherMap API Key。