javascript - jQuery 切换华氏/摄氏度

标签 javascript jquery openweathermap

我正在尝试使用开放天气 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&#176;</button>
        <button type="submit" id="btn2">C&#176;</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) + '&#176;');
$('#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/

相关文章:

javascript - 如何添加带有 "document.createTextNode"按钮的一行

jquery - 图像上的链接,不透明度悬停在图像上

javascript - m 自定义Scrollbar自动滚动问题

javascript - Emberjs 如何绑定(bind) id

javascript - 按钮同时有两个 Action

javascript - jQuery 类型函数作为变量

android - Openweathermap API获取当天的高温和低温

json - OpenWeatherMap 中的字符串值和天气图标

java - 尝试通过 JSON 查询从 openweathermap 获取数据时获取 FileNotFoundException

javascript - 在不重新加载侧边栏的情况下更新 Google Apps 脚本侧边栏中的内容