当前位置:首页 > JavaScript

js实现天气

2026-03-14 00:08:07JavaScript

使用 JavaScript 实现天气功能

获取天气 API

选择一个可靠的天气 API 服务,如 OpenWeatherMap、WeatherAPI 或 AccuWeather。这些服务通常提供免费的开发套餐,适合小型项目。注册账号后获取 API 密钥。

发起 API 请求

使用 fetchaxios 发起 HTTP 请求获取天气数据。以下是使用 fetch 的示例代码:

const apiKey = 'YOUR_API_KEY';
const city = 'Beijing';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

fetch(url)
  .then(response => response.json())
  .then(data => {
    console.log(data);
    displayWeather(data);
  })
  .catch(error => console.error('Error:', error));

解析并显示天气数据

从 API 返回的数据中提取所需信息,如温度、湿度、天气描述等,并将其显示在页面上。

js实现天气

function displayWeather(data) {
  const weatherDiv = document.getElementById('weather');
  const temp = data.main.temp;
  const humidity = data.main.humidity;
  const description = data.weather[0].description;

  weatherDiv.innerHTML = `
    <h3>Weather in ${data.name}</h3>
    <p>Temperature: ${temp}°C</p>
    <p>Humidity: ${humidity}%</p>
    <p>Description: ${description}</p>
  `;
}

处理用户输入

允许用户输入城市名称并触发天气查询。可以通过表单和事件监听器实现。

document.getElementById('weatherForm').addEventListener('submit', function(e) {
  e.preventDefault();
  const city = document.getElementById('cityInput').value;
  getWeather(city);
});

错误处理

确保在 API 请求失败或用户输入无效时提供友好的错误提示。

js实现天气

function getWeather(city) {
  fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error('City not found');
      }
      return response.json();
    })
    .then(data => displayWeather(data))
    .catch(error => {
      document.getElementById('weather').innerHTML = `<p>${error.message}</p>`;
    });
}

示例 HTML 结构

以下是一个简单的 HTML 结构,用于显示天气信息和用户输入表单。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Weather App</title>
</head>
<body>
  <form id="weatherForm">
    <input type="text" id="cityInput" placeholder="Enter city name" required>
    <button type="submit">Get Weather</button>
  </form>
  <div id="weather"></div>
  <script src="weather.js"></script>
</body>
</html>

完整代码示例

将上述代码整合到一个文件中,确保替换 YOUR_API_KEY 为实际的 API 密钥。

// weather.js
document.getElementById('weatherForm').addEventListener('submit', function(e) {
  e.preventDefault();
  const city = document.getElementById('cityInput').value;
  getWeather(city);
});

function getWeather(city) {
  const apiKey = 'YOUR_API_KEY';
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

  fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error('City not found');
      }
      return response.json();
    })
    .then(data => displayWeather(data))
    .catch(error => {
      document.getElementById('weather').innerHTML = `<p>${error.message}</p>`;
    });
}

function displayWeather(data) {
  const weatherDiv = document.getElementById('weather');
  const temp = data.main.temp;
  const humidity = data.main.humidity;
  const description = data.weather[0].description;

  weatherDiv.innerHTML = `
    <h3>Weather in ${data.name}</h3>
    <p>Temperature: ${temp}°C</p>
    <p>Humidity: ${humidity}%</p>
    <p>Description: ${description}</p>
  `;
}

通过以上步骤,可以实现一个简单的天气查询功能。根据需求可以进一步扩展,如添加图标、更多天气细节或缓存机制。

标签: 天气js
分享给朋友:

相关文章

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现论坛

js实现论坛

实现论坛的基本功能 使用JavaScript实现一个论坛需要结合前端和后端技术。前端可以使用React、Vue或Angular等框架,后端可以选择Node.js配合Express或Koa框架。数据库可…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js实现自举

js实现自举

实现 JavaScript 自举的方法 JavaScript 自举(Bootstrap)通常指通过 JavaScript 动态加载自身或依赖的脚本,实现运行时环境的初始化或扩展。以下是几种常见实现方式…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: functio…