Javascript 华氏至摄氏切换按钮
对于挑战,我需要创建一个按钮,在华氏温度和摄氏温度之间切换,我做到了。 问题是它工作到华氏温度,回到摄氏温度,然后停止。我希望用户可以随心所欲地来回切换,但我找不到解决方案Javascript 华氏至摄氏切换按钮,javascript,jquery,Javascript,Jquery,对于挑战,我需要创建一个按钮,在华氏温度和摄氏温度之间切换,我做到了。 问题是它工作到华氏温度,回到摄氏温度,然后停止。我希望用户可以随心所欲地来回切换,但我找不到解决方案 $("document").ready(function() { // Declaring global variables var latitude, longitude; // Getting the location to be shared in the weather API / Di
$("document").ready(function() {
// Declaring global variables
var latitude, longitude;
// Getting the location to be shared in the weather API / Display on Page
function getCurrentLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
// Getting exact location by passing Lat Long to Google Maps API
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&key=AIzaSyBBP3PtbN3vugWmPEia1aYeKNLP8_-VDck", function(json) {
console.log(JSON.stringify(json, null, 2));
$("#currentLocation").html(json.results[2].formatted_address);
// Getting exact Weather conditions by passing the Lat/Long to freeCodeCamp Weather API
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude, function(weatherJSON) {
$("#currentWeather").html(weatherJSON.weather[0].main + ", " + weatherJSON.weather[0].description);
$("#weatherIcon").attr("src", weatherJSON.weather[0].icon);
$("#currentTemp").html(weatherJSON.main.temp + " C°");
console.log(JSON.stringify(weatherJSON, null, 2));
// Converting Celsius to Farenheit
$(".btn").on("click", function setToF() {
var fahrenheit = (weatherJSON.main.temp * 9/5) + 32;
$("#currentTemp").html(fahrenheit + " F°");
$(".btn").html("Celsius");
if(weatherJSON.main.temp !== fahrenheit) {
$(".btn").on("click", function() {
$("#currentTemp").html(weatherJSON.main.temp + " C°");
$(".btn").html("Fahrenheit");
})
}
});
});
});
});
};
}
getCurrentLocation();
});
提前谢谢你的帮助 只需使用$('#currentTemp').html()
即可获得设定值(温度)
您可以保存当前的温度单位,并在每次决定从一个单位转换到另一个单位时引用它
weatherJSON.main.tempUnit = "C";
把你的.BTN点击处理程序拿出来。将其包装在函数中,并将weatherJSON.main.temp作为参数传递(如果存在且未定义)。然后它就会正常工作。您要在单击事件处理程序中添加单击事件吗?不要这样做与您的挑战无关,但最佳做法是:不要使用
.html()
来设置元素的文本内容,尤其是当该内容来自您无法控制的服务器时。你期待的是文本内容;显式设置文本内容。使用。@AuxTaco非常感谢。我喜欢这些最佳实践建议,因为老实说,我对我的代码不满意。我觉得从语法上讲可能会更好:)@JaromandaX实际上我正在学习,谢谢你的建议:)@Hacene.N一旦你的代码运行起来,你可以发布它来获得更多的最佳实践建议。谢谢:)这对我这个乞丐来说,以一种简单的方式帮助了我很多
weatherJSON.main.tempUnit = "C";