【问题标题】:On Click not updating the output of a function单击时不更新函数的输出
【发布时间】:2017-03-03 17:12:01
【问题描述】:
$('.btn').on("click", function() {
  var text = $(this).text();
  $(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
  changeUnits();
});

function changeUnits(Temp, c) {
  if ($('.btn').text() === 'Celsius')   
    return Math.round((Temp - 273.15)*10)/10 + " &degC";
  else
  return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}

我正在尝试使用单击事件上的按钮来更改临时显示,但它似乎不像这样工作。无论如何,该功能都会看到摄氏度。我也试过 $(this).html 。按钮的文本实际上正在改变,只是功能没有更新。我也尝试在按钮单击中运行更改单位功能,但它仍然没有更新。

我对这个 onclick 事件有什么不明白的地方以及如何让它工作。

JS代码:

    var apiKey = "get your own key from http://openweathermap.org";

  function changeUnits(Temp, c) {
  if ($('.btn').text() === 'Celsius')   
    return Math.round((Temp - 273.15)*10)/10 + " &degC";
  else
  return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}

$('.btn').on("click", function() {
  var text = $(this).text();
  $(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
  changeUnits();
});

$(function() {
  var loc;
  //api call to get lat and long
  $.getJSON('http://ipinfo.io', function(data) {
    loc = data.loc.split(",");

    //weather API call
    $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
      loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
      function(weather) {
        var currentLocation = weather.name;
        var currentConditions = weather.weather[0].description;
        var currentTemp = changeUnits(weather.main.temp);
        var high = changeUnits(weather.main.temp_max);
        var low = changeUnits(weather.main.temp_min);
        var currentWind = weather.wind.speed;
        var currentWdir = weather.wind.deg;
        var sunRise = weather.sys.sunrise;
        var sunSet = weather.sys.sunset;
        var icon = weather.weather[0].icon;
        //set HTML elements for weather info
        $('#currentLocation').append(currentLocation);
        $('#currentTemp').html(currentTemp);
        $('#high-low').html('<span id="high">High: ' + high + '</span><br>' 
                            + '<span id="low">Low: ' + low + '</span>');
        $('#currentConditions').html(currentConditions);

        var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
        $('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
      });
  });
});

HTML:

<html>
<head>
    <meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
    <title></title>
</head>
<body>
  <div id="header">
    <div class="left"><h1 id="currentLocation">Your Current Location is  </h1></div>
    <div class="navbar"></div>
    <div class="right"><a href="https://github.com/Maverick494"><i class="fa fa-github bigger_icon"></i></a></div>
  </div>
  <div id="container">
    <h2 class="text-center content-title" id="currentTemp"></h2>
    <div class="content-body text-center">
      <p id="high-low"></p>
      <button data-text-swap="Fahrenheit" id="unitButton" type="button" class="btn btn-success">Celsius</button>
      <p id="currentConditions"></p>
    </div>
  </div>
</body>
</html>

我已经做了所有我能想到的改变。 onclick 中的 console.log(el.text()) 清楚地显示了文本的变化;但是当我在 onclick 期间再次运行该函数时,changeUnits 的函数似乎永远不会在 if 语句中提取它。

【问题讨论】:

  • 您能否创建一个小提琴示例链接,以便我们也可以检查 html 部分。我们无法重现您的问题,因此我们可以纠正它。
  • 我认为你的方法是错误的,为什么使用 class .btn 而不是使用 ID,如果你在按钮单击时调用它,你将创建循环依赖
  • 你在click函数中的c和f参数是从哪里得到的?
  • 在原问中加了笔
  • 我使用了这个类,因为我只有一个按钮用于这个简单的项目,但后来我将它更新为按钮的ID,它仍然不起作用。

标签: javascript jquery


【解决方案1】:

看起来您使用的是html() 而不是text()。我假设您正在寻找按钮文本而不是 html,所以试试这个:

$('.btn').on("click", function() {
  $(this).text(function(f, c) {
    return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
  });
});

function changeUnits(Temp, c) {
  if ($('.btn').text() === 'Celsius'){
    return Math.round(Temp - 273.15) + " &degC";
  }else{
    return Math.round((Temp* (9/5)) - 459.67) + " &degF";
  }
}

【讨论】:

  • 我试过这个,但它似乎也没有工作。我会发布我最终做的事情。
【解决方案2】:

你没有调用函数,在代码中读取 cmets 此外,您没有将任何信息传递给传递给 text 方法的函数中的“.btn”。

$('.btn').on("click", function() {
  var text = function(f, c) {  // where are you getting your f and c parameters?
        console.log(f); // should be undefined
        console.log(c); // should be undefined
        return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
      }();
  console.log(text); // should be 'Celsius'
  $(this).text(text);   // changed from })  to }())
});


function changeUnits(Temp, c) {
  if ($('.btn').text() === 'Celsius')   //  change html() to text() as well
    return Math.round(Temp - 273.15) + " &degC";
  else
  return Math.round((Temp* (9/5)) - 459.67) + " &degF";
}

此外,您应该使用 ID 来关联您的按钮以执行此操作

<input id='thisID'>
// then call it in javascript
$("#thisID")

切换按钮

$('.btn').on("click", function() {
  var text = $(this).text();
  $(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
});

【讨论】:

  • 嗯,f和c参数,看了之后,不知从何而来;也就是说,如果没有它们,按钮文本不会改变。当我从 }) 更改为 }()) 时,点击不再更改按钮文本。我也一定没有提到我也尝试过 .text() ,但它仍然不起作用。我可以使用 ID 我有一个“unitButton”按钮的 ID
  • 另外,我是否需要将任何内容传递给 onclick 按钮?我以为我只是在阅读按钮文本是什么并基于此更新功能。我想我需要一种方法来在那里重新运行 changeUnits 函数。我曾尝试将 changeUnits() 放在 onclick 几次/地方,但没有帮助
  • 还有一件事,如果我进入我的 HTML 并删除单词 Celsius 它会改变。所以我知道更改单位功能正在发挥作用。它就像按钮文本的变化实际上并没有在 HTML 中发生变化。所以也许这是我错的部分。
  • 将所有代码的代码笔添加到原始问题中
  • 您没有更改文本。试试我的编辑版本
【解决方案3】:

我认为这是您的问题。我没有去测试它,因为我需要获取天气 API 和其他东西。通过查看您的代码,我得到了以下信息。

当页面加载时,您将从 OpenWeatherMap 获取天气数据。但是,您不会在某种全局变量中兑现此信息,以便您以后访问它。您已经在 ajax 回调中声明了所有变量,以后无法访问它们。

尝试这样做:

var currentTemp;
var high;
var low;

$(function() {
  var loc;
  //api call to get lat and long
  $.getJSON('http://ipinfo.io', function(data) {
    loc = data.loc.split(",");

    //weather API call
    $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
      loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
      function(weather) {
        var currentLocation = weather.name;
        var currentConditions = weather.weather[0].description;
        currentTemp = weather.main.temp;
        high = weather.main.temp_max;
        low = weather.main.temp_min;
        var currentWind = weather.wind.speed;
        var currentWdir = weather.wind.deg;
        var sunRise = weather.sys.sunrise;
        var sunSet = weather.sys.sunset;
        var icon = weather.weather[0].icon;
        //set HTML elements for weather info
        $('#currentLocation').append(currentLocation);
        updateDisplay();
        $('#currentConditions').html(currentConditions);

        var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
        $('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
      });
  });
});

function changeUnits(Temp) {
  if ($('.btn').text() === 'Celsius')   
    return Math.round((Temp - 273.15)*10)/10 + " &degC";
  else
  return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}

$('.btn').on("click", function() {
  var text = $(this).text();
  $(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
  updateDisplay();
});


function updateDisplay(){
      $('#currentTemp').html(changeUnits(currentTemp));
      $('#high-low').html('<span id="high">High: ' + changeUnits(high) + '</span><br>' 
                                    + '<span id="low">Low: ' + changeUnits(low) + '</span>');
}

我引入了另一个函数 updateDisplay() 来实际处理显示温度的变化。正如我所说,我没有测试它。但我很确定它会起作用。

【讨论】:

    【解决方案4】:

    JS:

    var apiKey="get an openweathermap APIKey";    
    var loc;
    var lat;
    var long;
    
    var temp;
    var high;
    var low;
    var icon;
    //var wind;
    //var windDir;
    //var windSpd;
    
    //api call to get lat and long
    $.getJSON('http://ipinfo.io', function(data) {
      loc = data.loc.split(",");
      lat = parseFloat(loc[0]);
      long = parseFloat(loc[1]);
      getWeather(lat, long);
      initGmaps(lat, long);
    });
    
    //api call to use lat and long to generate a map
    window.addEventListener('load', function() {
    
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = '?key=AIzaSyDKgEmSnYmFmbhQVGY8K6NXxV5ym2yZXdc&callback=initMap';
      document.body.appendChild(script);
    });
    
    function initGmaps(lat, long) {
     var map = new GMaps({
        div: '#map',
        lat: lat,
        lng: long,
        zoom: 14,
        disableDefaultUI: true,
        mapTypeId: "satellite",
      });
    map.addMarker({
      lat: lat,
      lng: long
    });
    }
    
    //using weather to get data and plug it into our page
    function getWeather(lat, long) {
      var api = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
        lat + '&lon=' + long + '&appid=' + apiKey;
    
      $.ajax({
        url: api,
        dataType: 'json',
        success: function(data) {
          temp = {
            f: Math.round(((data.main.temp * 9 / 5) - 459.67) * 100) / 100 + " °F",
            c: Math.round(((data.main.temp - 273.15)) * 100) / 100 + " °C"
          };
          high = {
            f: Math.round(((data.main.temp_max * 9 / 5) - 459.67) * 100) / 100 + " °F",
            c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
          };
          low = {
            f: Math.round(((data.main.temp_min * 9 / 5) - 459.67) * 100) / 100 + " °F",
            c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
          };
    
          windSpd = {
            f: Math.round((data.wind.speed * 2.23694)*10)/10 + " MPH",
            c: Math.round((data.wind.speed)*10)/10 + " M/S"
          };
    
          var windArr = ["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
    
          var windDir = windArr[Math.floor(((data.wind.deg/22.5)+.5))]; 
    
          $('#currentLocation').append(data.name);
          $('#high').append(" " + high.f);
          $('#low').append(" " + low.f);
          $('#currentTemp').html(temp.f);
          $('#weatherDesc').html(data.weather[0].description);
          $('#windDir').html(windDir);
          $('#windDir').append('<span id="windSpd">' + windSpd.f + '</span>');            
    
    
          icon = data.weather[0].icon;
          var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
          $('#currentConditions').html('<img id="weatherImg" src="' + iconSrc + '"><br>');
        }
      });
    }
    
    $('#currentTemp').on('click', function() {
      var current = $(this).data('nexttemp');
      $('#currentTemp').text(temp[current]);
      $('#high').html(high[current]);
      $('#low').html(low[current]);
      $('#windSpd').html(windSpd[current]);
    
      if (current == 'c') {
        $(this).data('nexttemp', 'f');
        return;
      }
      $(this).data('nexttemp', 'c');
    });
    

    HTML:

    <html>
    <head>
        <meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
        <title></title>
    </head>
    <body>
      <div id="header">
        <div class="left"></div>
        <div class="navbar"><h4>Free Code Camp Weather App</h4></div>
        <div class="right"><a href="https://github.com/Maverick494"><i class="fa fa-github bigger_icon"></i></a></div>
      </div>
        <div id="container">
          <div class="col-lg-4" id="map"></div>
          <div class="col-lg-4">
          <h1 id="currentLocation">Your Current Location is </h1>
          </div>
          <h2 class="center-text content-title" id="currentTemp"></h2>
          <h3 id="caption">Click temperature to change Units</h3>
          <div class="center-text">
          <p class="oneLine" id="labels">High: <span id="high"></span></p>
          <p class="oneLine" id="labels">Low:  <span id="low"></span></p>
          </div>
          <p class="center-text" id="currentConditions"></p>
          <p class="center-text" id="weatherDesc"></p>
          <div class="windCompass col-lg-4">
            <div class="compass">
              <div class="direction">
                <p id="windDir"></p>
              </div>
              <div class="arrow ne"></div>
            </div>
          </div>
        </div>
     </body>
    </html>
    

    CSS:

    @import url(http://fonts.googleapis.com/css?family=Dosis:200,400,500,600);
    
    body {
        background: url(http://eskipaper.com/images/pixel-backgrounds-1.jpg);
        background-size: auto;
      background-repeat: no-repeat;
        font-family: Ranga, cursive;
    }
    
    h4 {
      margin-top: 7px;
    }
    
    h1 {
        margin-left: -7px;
      font-size: 1.05em;
        color: white;
    }
    
    #header {
        background: #2980b9;
        color: white;
        padding: 0 5px;
        display: inline-block;
        width: 100%;
        margin: 0;
        box-shadow: 0 2px 5px #555555;
    }
    
    #header .left {
        display: inline-block;
        width: auto;
        float: left;
        margin-top: 7px;
        margin-left: 7px;
    }
    
    #header .navbar {
        display: inline-block;
        width: 60%;
    }
    
    #header .right {
        display: inline-block;
        width: auto;
        text-align: right;
        float: right;
        margin-top: 2px;
        margin-right: 7px;
        vertical-align: bottom;
    }
    
    .bigger_icon {
        margin-top: 10px;
      font-size: 2em;
        color: white;
    }
    
    #map {
        height: 200px;
        width: 200px;
        border-radius: 5%;
        margin-top: 20px;
    }
    
    #container {
        background: rgba(66, 66, 66, 0.6);
        display: block;
        position: relative;
        width: 40%;
        margin: 24px auto;
        min-height: 300px;
        padding: 16px;
        border-radius: 4px;
    }
    
    #container .center-text {
        text-align: center;
    }
    
    h2 {
        color: white;
        font-family: Ranga, cursive;
        font-size: 2.5em;
        font-weight: bold;
        margin-top: -230px;
    }
    
    #caption {
        font-size: 17px;
        text-align: center;
        color: pink;
    }
    
    #labels {
        color: darkGrey;
        font-size: 1.5em;
    }
    
    .oneLine {
        color: darkGrey;
        font-size: 1.5em;
        text-align: center;
        display: inline;
        padding: 5px;
    }
    
    #high {
        text-align: center;
        color: orange;
    }
    
    #low {
        text-align: center;
        color: blue;
    }
    
    #currentConditions {
        text-align: center;
        color: black;
    }
    
    #weatherDesc {
        margin-top: -25px;
        color: white;
    }
    
    .windCompass {
        margin-left: 75%;
        margin-top: -20%;
    }
    
    .compass {
        display: block;
        width: 120px;
        height: 120px;
        border-radius: 100%;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.85);
        position: relative;
        font-family: 'Dosis';
        color: #555;
        text-shadow: 1px 1px 1px white;
    }
    
    .compass:before {
        font-weight: bold;
        position: absolute;
        text-align: center;
        width: 100%;
        content: "N";
        font-size: 14px;
        top: -2px;
    }
    
    .compass .direction {
        height: 100%;
        width: 100%;
        display: block;
        background: #f2f6f5;
        background: -moz-linear-gradient(top, #f2f6f5 30%, #cbd5d6 100%);
        background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f2f6f5), color-stop(100%, #cbd5d6));
        background: -webkit-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
        background: o-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
        border-radius: 100%;
    }
    
    .compass .direction p {
        text-align: center;
        margin: 0;
        padding: 0;
        position: absolute;
        top: 50%;
        left: 0;
        width: 100%;
        height: 100%;
        line-height: 80px;
        display: block;
        margin-top: -35%;
        font-size: 28px;
        font-weight: bold;
    }
    
    .compass .direction p span {
        display: block;
        line-height: normal;
        margin-top: -10%;
        font-size: 17px;
        text-transform: uppercase;
        font-weight: normal;
      font-family: Ranga, cursive; 
    }
    
    .compass .arrow {
        width: 100%;
        height: 100%;
        display: block;
        position: absolute;
        top: 0;
    }
    
    .compass .arrow:after {
        content: "";
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 10px solid red;
        position: absolute;
        top: -6px;
        left: 50%;
        margin-left: -5px;
        z-index: 99;
    }
    
    .compass .arrow.nne {
        transform: rotate(22.5deg);
    }
    
    .compass .arrow.ne {
        transform: rotate(45deg);
    }
    
    .compass .arrow.ene {
        transform: rotate(67.5deg);
    }
    
    .compass .arrow.e {
        transform: rotate(90deg);
    }
    
    .compass .arrow.ese {
        transform: rotate(112.5deg);
    }
    
    .compass .arrow.se {
        transform: rotate(135deg);
    }
    
    .compass .arrow.sse {
        transform: rotate(157.5deg);
    }
    
    .compass .arrow.s {
        transform: rotate(180deg);
    }
    
    .compass .arrow.ssw {
        transform: rotate(202.5deg);
    }
    
    .compass .arrow.sw {
        transform: rotate(-135deg);
    }
    
    .compass .arrow.wsw {
        transform: rotate(-114.5deg);
    }
    
    .compass .arrow.w {
        transform: rotate(-90deg);
    }
    
    .compass .arrow.wnw {
        transform: rotate(-69.5deg);
    }
    
    .compass .arrow.nw {
        transform: rotate(-45deg);
    }
    
    .compass .arrow.nnw {
        transform: rotate(-24.5deg);
    }
    

    我最终找到了一些 Ajax 并使用它来完成我期望按钮执行的操作。虽然不是按钮,但它可以执行预期的操作。我还致力于改变高、低和风速,以随着单位的变化而变化。

    感谢大家提供的帮助。

    如果您愿意,请随时提供有关代码的建议以及修复指南针渐变的 css 并使愚蠢的东西更具响应性。 (地图没有做响应式的事情。

    【讨论】:

      【解决方案5】:

      您的脚本可能在 DOM 准备好之前就已加载。

      您想要在此处执行的操作是以下几个选项之一: 1.在body末尾加载JS脚本标签。 2. 用 document.on('ready') 事件包装你的 $('.btn').on(...) 函数,这样这段代码只会在 DOM 准备好时触发。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-21
        • 2021-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多