我正在尝试使用开放天气 map API 创建天气应用程序。我想创建一个按钮,允许您在华氏度和摄氏度之间切换。我已经尝试了几乎所有的方法,但我又回到了在尝试放入按钮之前编写的代码。
如何使用当前设置实现此目的?
<div class="container">
<div class="jumbotron text-center"
style="background-color: #00F0F8FF; font-family: 'Oswald', sans-
serif; color: black;">
<h1>Local Weather App</h1>
<h2><span id="town"></span></h2>
<h2>Temperture: <span id="temp"></span></h2>
<div id="weatherIconBox"></div>
<h2><span id="weatherType"></span></h2>
<button type="submit" id="btn1">F°</button>
<button type="submit" id="btn2">C°</button>
</div>
</div>
var getIP = 'http://ip-api.com/json/';
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather'
$.getJSON(getIP).done(function(location) {
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
units: "imperial",
}).done(function(data) {
$('#town').html(data.name);
$('#temp').prepend(Math.floor(data.main.temp) + '°');
$('#weatherType').html(data.weather[0].description).css('textTransform', 'capitalize');
$('#weatherIconBox').prepend('<img id="weatherIcon" src="http://openweathermap.org/img/w/' + data.weather[0].icon + '.png"/>');
});
});
最佳答案
当您单击“#temp”元素时,此代码将在摄氏度和华氏度之间切换文本
var cToF = function(c) {
return (c * (9/5)) + 32;
};
var fToC = function(f) {
return (f - 32) * (5/9);
};
$("#temp").on("click", function() {
var isF = $(this).data("units") === "f";
var oldTemp = $(this).text();
var newTemp = isF ? fToC(oldTemp) : cToF(oldTemp);
$(this).text(newTemp);
var newUnits = isF ? "c" : "f";
$(this).data("units", newUnits).attr("data-units", newUnits);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Temperature: <span id="temp" data-units="f">100</span></h2>
<h2>Temperture: <span id="temp"></span></h2>
关于javascript - jQuery 切换华氏/摄氏度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44786657/