要在JavaScript中显示天气,通常需要以下几个步骤:
以下是一个简单的示例,展示如何使用JavaScript和OpenWeatherMap API获取并显示当前天气:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
</head>
<body>
<h1>Current Weather</h1>
<div id="weatherInfo"></div>
<script src="app.js"></script>
</body>
</html>
const apiKey = 'YOUR_API_KEY'; // 替换为你的OpenWeatherMap API密钥
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 => {
const weatherInfo = document.getElementById('weatherInfo');
weatherInfo.innerHTML = `
<p>City: ${data.name}</p>
<p>Temperature: ${data.main.temp}°C</p>
<p>Condition: ${data.weather[0].description}</p>
`;
})
.catch(error => {
console.error('Error fetching weather data:', error);
});
通过以上步骤和示例代码,你可以实现一个基本的天气显示功能。如果有更多具体问题或需要进一步的功能扩展,可以根据具体需求进行调整和优化。
领取专属 10元无门槛券
手把手带您无忧上云