var tempreture = document.getElementById("temp")
var requestWeather = new XMLHttpRequest();
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getTemp(weatherData);
}; requestWeather.send();
function getTemp(data) {
var tempString = "";
var temp = data.main.temp;
tempString += "<p class='weather'>" + temp + '℃' + "</p>";
tempreture.innerHTML = tempString;
tempreture.addEventListener("click", function( ) {
var ftemp = "<p class='weather'>" + changeTemp(temp) + '° F' + "</p>";
tempreture.innerHTML = ftemp;
},false);
}
function changeTemp(temp){
var tp = temp * 1.8 + 32;
var cel =Math.round(tp);
return cel;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="temp" onclick="getTemp()"></a>
如何使用click
回调处理程序交换其他字符串中的文字
当用户点击元素时,我想在华氏度和摄氏度之间切换。
这是我到目前为止所做的:
function getTemp(data) {
var tempString = "";
var temp = data.main.temp;
tempreture.addEventListener("click", function( ) {
tempString += "<p class='weather'>" + temp + '℃' + "</p>";
},false)
tempString += "<p class='weather'>" + changeTemp(temp) + '° F' + "</p>";
tempreture.insertAdjacentHTML("beforeend", tempString);
}
function changeTemp(temp){
var tp = (temp - 32) * 5/9;
var cel =Math.round(tp);
return cel;
};
我只使用纯javascript尝试过这个。如果有人能给我一个关于我做错了什么的提示,那将是很棒的。
var temp = data.main.temp;
temp是我从中获取数据的地方,并传递给HTML。我已完成转换,但我不知道如何从转换函数传回来。
ADD 温度数据来自
var requestWeather = new XMLHttpRequest();
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=' + data.lat + '&lon=' + data.lon);
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getTemp(weatherData);
}
编辑我现在尝试过点击功能。但是,我发现点击后返回旧值时会出现同样的问题。
答案 0 :(得分:3)
我建议您验证API返回的数据。
var tempreture = document.getElementById("temp")
var requestWeather = new XMLHttpRequest();
// global cache
var currentTemp,
currentUnit;
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getTemp(weatherData);
};
requestWeather.send();
function getTemp(data) {
currentTemp = typeof data === 'object' ? data.main.temp : null; // save new value in global cache
currentUnit = 'celcius';
tempreture.innerHTML = currentTemp + '℃';
}
tempreture.addEventListener("click", function() {
tempreture.innerHTML = changeTemp();
}, false);
function changeTemp() {
if(currentUnit === 'celcius') {
var tp = currentTemp * 1.8 + 32;
var fh = Math.round(tp);
currentUnit = 'fahrenheit';
return fh + '° F';
} else {
currentUnit = 'celcius';
return currentTemp + '℃';
}
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="temp" class='weather'></span>
&#13;