jQuery Click事件只触发一次

时间:2017-08-21 03:16:16

标签: jquery

出于某种原因,我只能在温度元素(id:#temp)上触发click事件。在它转换为华氏温度后,它不会转换回摄氏温度。我刚开始使用jQuery,所以任何帮助都会非常感激。源代码如下。

HTML来源:

<html>
  <head>
    <link rel="stylesheet" href="main.css"/>
    <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
    <script src="main.js"></script>
    <script type="text/javascript" async src="https://platform.twitter.com/widgets.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"></link>
  </head>

  <body>
    <h1>Local Weather Code Camp Project</h1>
    <h4>Location</h4>
    <p id="location"></p>
    <h4>Weather</h4>
    <p id="weather"></p>
    <img id="icon">
    <h3 id="temp"></h3>
    <p id="check"></p>
  </body>
</html>

jQuery来源:

$(document).ready(function () {
 navigator.geolocation.getCurrentPosition(function(position) {
   $.getJSON('https://fcc-weather-api.glitch.me/api/current?lat=' + position.coords.latitude + '&lon=' + position.coords.longitude , function(data){
     var tmpInt = 0;
     $("h1").html(JSON.stringify(data));
     $("#location").html(data.name);
     $("#weather").html(data.weather[0].description);
     $("#icon").attr("src", data.weather[0].icon);
     $("#temp").html(data.main.temp + "&#176; C");
     $(document).on('click','#temp',function() {
       tmpInt = data.main.temp;
       tmpInt = tmpInt * 1.8 +32;
       if("#temp:contains('&#176; C')") {
          $("#temp").html(tmpInt + "&#176; F");
          $("#check").html("Contains C");
       }
       else if("#temp:contains('&#176; F')") {
         $("#temp").html(data.main.temp + "&#176; C");
         $("#check").html("Contains F");
       }
     });
   });
 });
});

使用CodePen here

2 个答案:

答案 0 :(得分:0)

首先,这个

if("#temp:contains('&#176; C')")

一样有用
if('any non-empty string')

相当于

if(true)

无论如何,我建议您使用更好的标志来指示当前显示的温标。尝试使用.data API,例如

$("#temp").html(data.main.temp + "&#176; C").data('unit', 'C');

并在您的点击处理程序中

var temp = $(this); // no need to keep looking this up by ID
switch (temp.data('unit')) {
  case 'F':
    // set temp in C, etc
    temp.data('unit', 'C') // set the unit flag
  case 'C':
  default:
    // set temp in F, etc
    temp.data('unit', 'F') // set the unit flag
}

答案 1 :(得分:0)

条件始终评估为true,因此temp始终更改为F.

使用另一个变量来记住显示的单位(C或F)有效......

    var units = 'C';

    $("#temp").on("click", function() {
      tmpInt = data.main.temp;
      tmpInt = tmpInt * 1.8 + 32;

      if (units == 'C') {
        $("#temp").html(tmpInt + "&#176; F");
        units = 'F';
      } else if (units == 'F') {
        $("#temp").html(data.main.temp + "&#176; C");
        units = 'C';
      }
    });