我正在ES6中构建一个简单的气象应用程序,该应用程序应该从Spotify返回一首适合当前天气和天气预报的歌曲。但是,当用户连续两次针对不同的位置执行搜索时,仍会显示第一次搜索中的歌曲。
当前,我用显示隐藏CSS中的歌曲轨道:无,然后根据通过if语句的搜索结果将显示更改为在JS中阻止。 如何从第一首搜索中删除第一首歌曲?
我尝试将if语句更改为switch语句,但是它完全停止显示歌曲。我想到的另一个选择是使用classList,但是我不确定如何...
CSS
#musicRain,
#musicClear,
#musicThunderstorm,
#musicSnow,
#musicClouds,
#musicAtmosphere {
display: none;
}
JS
function showCurrentWeather(response) {
let currentTemperature = document.querySelector("#currentTemperature");
currentTemperature.innerHTML = `${Math.round(response.data.main.temp)}°C`;
[etc... ]
if (response.data.weather[0].main === "Clear") {
document.getElementById("musicClear").style.display = "block";
}
if (response.data.weather[0].main === "Drizzle") {
document.getElementById("musicDrizzle").style.display = "block";
}
if (response.data.weather[0].main === "Rain") {
document.getElementById("musicRain").style.display = "block";
}
if (response.data.weather[0].main === "Clouds") {
document.getElementById("musicClouds").style.display = "block";
} else {
document.getElementById("musicAtmosphere").style.display = "block";
}
}
答案 0 :(得分:0)
您希望将每个元素的display
字段设置为block
或none
,以免保留较早的设置。由于它们都是以“音乐”开头的,因此您可以这样做:
const types = ["Clear","Drizzle","Rain","Clouds","Atmosphere"];
types.forEach( type => {
const musicType = `music${type}`
if (response.data.weather[0].main === type) {
document.getElementById(musicType).style.display = "block";
}
else {
document.getElementById(musicType).style.display = "none";
}
});