大家好,我是新人,所以请保持友善:)
--编辑 2:这就是我现在要做的
colorChange: function(data) {
console.log(data.main.temp);
var tempColor= this.displayWeather(document.querySelector(data.main.temp).value);
if(tempColor<=10){
document.body.style.backgroundColor="lightgrey";
}
else if(tempColor>=11&&tempColor<20){
document.body.style.backgroundColor="lightblue";
}
else{
document.body.style.backgroundColor="lightcoral";
}
}
问题似乎是它无法找到“temp”,并且当我尝试控制台记录它时,它返回未定义。
感谢大家之前的帮助>。<
--编辑:我已经更新了代码,但它似乎仍然不起作用,任何帮助将不胜感激--
colorChange: function() {
if (temp.innerText<=10){
document.body.style.backgroundColor="lightgrey";
}
else if (temp.innerText> 11 && temp.innerText<20){
document.body.style.backgroundColor="lightblue";
}
else{
document.body.style.backgroundColor="lightcoral";
}
}
在 Javascript 中,函数是使用
function name(params){ ... }
定义的。如果你想从它的类中获取一个元素,你可以使用 document.querySelector(".class")
。不过,此方法会获取页面上具有该类的第一个元素。但如果您想要一个名为该变量的变量而不是 DOM 元素,只需按原样键入该变量即可。我还建议将 colorChange 函数放入循环或其他函数中。您的代码如下所示:
function colorchange(){
var tempColor = data.main.temp.value;
if (tempColor <= 20){
document.body.style.backgroundColor="lightblue";
}
else if (20 < tempColor && tempColor < 40) { //I added this in to show you how you can add more conditions, using else if.
document.body.style.backgroundColor="blue";
}
else {
document.body.style.backgroundColor="red";
}
}
为了获取数据,您必须从 API 端点获取数据,如下所示
let colorChange = async function () {
const response = await fetch("https://api.openweathermap.org/data/2.5/weather?q=Denver&units=metric&appid=API_KEY");
const data = await response.json();
console.log(data);
let tempColor = data.main.temp;
if (tempColor <= 10) {
document.body.style.backgroundColor = "lightgrey";
}
else if (tempColor >= 11 && tempColor < 20) {
document.body.style.backgroundColor = "lightblue";
}
else {
document.body.style.backgroundColor = "lightcoral";
}
}
不要忘记将
&appid=API_KEY
替换为您的 API 密钥
有关 fetch 的更多信息可以在here找到,有关异步函数的更多信息可以在here
找到我还添加了
&units=metric
作为参数,以便您以摄氏度接收它