javascript - jQuery replaceWith 不起作用

标签 javascript jquery

在我的 JS 中,我假装在华氏度和摄氏度之间切换,但是当我尝试通过 $("#temp").replaceWith(temp) 更改 html 时,没有任何反应,如您在此处看到的:https://codepen.io/brunofigalves/pen/KRWdQo/

这是我用来执行此操作的代码片段

$(document).ready(function(){
  var lat, lon, temp;
  var isCelsius = true;

  $("#fahrenheit").click(function() {
    if(isCelsius) {
      temp = Math.round(temp*9/5 + 32);
      $("#temp").replaceWith(temp);
      isCelsius = false;
    }
    console.log(temp); 
  });
  $("#celsius").click(function() {
    if(!isCelsius) {
      temp = Math.round((temp-32)*(5/9));
      $("#temp").replaceWith(temp);
      isCelsius = true;
    }
    console.log(temp);
  });

});

最佳答案

你必须给 temp 一个初始值。默认情况下,它是 undefined 导致您的计算无法按预期工作。

虽然给 temp 一个值,修复你的 NaN 问题,你只能将你的值转换为 (#temp).replaceWith() 没有像您预期的那样工作。它将替换完整的元素,并在第一次后将其从 DOM 中移除。

参见 replacewith了解更多详情。

在这种情况下使用 $(#temp).text(temp) 似乎可行。

为了示例,我已将下面的初始 temp 设置为 0。这样它就可以在 032

之间切换

$(document).ready(function() {
  var lat, lon, temp = 0;
  var isCelsius = true;

  $("#time").text(updateTime);

  function updateTime() {
    let d = new Date();
    var dayString = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
    return dayString[d.getDay() - 1] + ", " + d.getHours() + ":" + d.getMinutes();
  }
  $("#fahrenheit").click(function() {
    if (isCelsius) {
      temp = Math.round(temp * 9 / 5 + 32);
      $("#temp").text(temp);
      isCelsius = false;
    }
    console.log(temp);
  });
  $("#celsius").click(function() {
    if (!isCelsius) {
      temp = Math.round((temp - 32) * (5 / 9));
      $("#temp").text(temp);
      isCelsius = true;
    }
    console.log(temp);
  });


  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(updateCoordinates);
  } else {}

  function updateCoordinates(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    getWeatherInfo();
  }

  function getWeatherInfo() {
    $.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + lat + "&lon=" + lon, function(data) {
      $("#location").replaceWith(data.name + ", " + data.sys.country);
      $("#summary").replaceWith(data.weather[0].main + ", " + data.weather[0].description);
      temp = Math.round(data.main.temp);
      $("#temp").replaceWith(temp);
      updateImage(data.weather[0].description);
    });
  }

  function updateImage(forecast) {
    switch (forecast) {
      case "clear sky":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-day-sunny");
        break;
      case "few clouds":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-day-cloudy");
        break;
      case "scattered clouds":
      case "broken clouds":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-cloudy");
        break;
      case "shower rain":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-day-rain-mix");
        break;
      case "rain":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-rain");
        break;
      case "thunderstorm":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-thunderstorm");
        break;
      case "snow":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-snow");
        break;
      case "mist":
        $("#img-weather").removeClass();
        $("#img-weather").addClass("wi wi-fog");
        break;
    }
  }

});
@import "https://rawgit.com/bomholtm/fcc/master/_assets/css/weather-icons.min.css";
.jumbotron {
  background: linear-gradient(45deg, #2E3192, #1BFFFF);
  color: white;
  padding-left: 20px;
}

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

div {
  transition-property: all;
  transition-duration: 5s;
}

.container-weather {
  margin-top: 50px;
}

#img-weather {
  font-size: 80px;
  margin-left: 50px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<link rel="stylesheet" href="https://rawgit.com/bomholtm/fcc/master/_assets/css/font-awesome.min.css">
<main class="container">
  <div class="jumbotron center">
    <h1 class="display-5"><a id="location">Loading data</a></h1>
    <h2 class="lead"><a id="time">time<a/></h2>
      <h2 class="lead"><a id="summary">summary<a/></h2>
      <div class="row container-weather">
        <h2 class="display-2"><a id="temp">0<a/></h2>
        <a id="celsius" href="#">°C</a>|<a id="fahrenheit" href="#">°F</a>
      <div id="img-weather"></div>
  </div>

  <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
        View more
      </button>
  <div class="collapse" id="collapseExample">
    <div class="card card-body">
      Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
    </div>
  </div>
  </div>
</main>


<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>

关于javascript - jQuery replaceWith 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50118341/

相关文章:

javascript - 如何在react.js文件中编写php脚本?

javascript - jquery 实时打字

javascript - 如何通过单击按钮更改 Google map 中心

javascript - 设置目标后如何重新启动 Orbit Controls

javascript - Css3 媒体查询 polyfill

javascript - 每当我返回窗口时,我的 setInterval 方法都会出现问题

jquery - 是否有一个 jQuery 解决方案,在可用时使用 CORS,并在 MSIE 上使用 XDomainRequest,在浏览器上使用 niether 时使用 JSONP?

javascript - Shiny + JS : Conditional Formatting based on Pivot Values

javascript - 将每三个 div 包装为一个

javascript - 将事件添加到 Rickshaw 中的 Series.Toggle