javascript - 添加第二个类不起作用

标签 javascript jquery css ajax

我已经在这个问题上苦苦挣扎了几天,但没有找到合适的解决方案。希望有人能帮忙。我想要实现的是允许用户单击“更改位置”,输入位置并让该输入指示为“天气”设置的背景图像。问题是代码在第一次单击按钮时有效,但在第二次单击时无效。为什么会这样?

这是 CodePen .

我有以下 Javascript 代码:

// Dynamic buttons
var inputs = document.getElementsByTagName('input');

for (var i = 0, len = inputs.length; i < len; i++) {
  input = inputs[i];
  input.onmouseover = function() {
    this.setAttribute('data-orig-image', this.getAttribute('src'));
    this.src = this.getAttribute('data-alt-image');
  };
  input.onmouseout = function() {
    this.src = this.getAttribute('data-orig-image');
  };
};

//Get location
var getLocation = $.ajax({
  type: 'GET',
  url: "http://ipinfo.io/json",
});

//Once location is received, wrap get weather with returned data/function
getLocation.done(function(data) {
  //Set user's current location 
  var location = data.city;
  //Set user location on page
  $(".location").html(location);
  //Get weather for user's current location
  var getWeather = $.ajax({
    type: 'GET',
    url: "http://api.openweathermap.org/data/2.5/weather?q='" + location + "&APPID=4b3ff62e3ed31d05cb44a014d891b7e6",
  });
  //Once received do stuff with data!
  getWeather.done(function(data) {
    var temp = data.main.temp;

    var kelvinDegrees = temp;
    var imperialDegrees = ((kelvinDegrees * (9 / 5)) - 459.67);
    var truncatedImperial = Math.floor(imperialDegrees * 100) / 100;
    var metricDegrees = kelvinDegrees - 273.15;
    var truncatedMetric = Math.floor(metricDegrees * 100) / 100;

    $(".degrees").html(truncatedImperial);

    var shown = 1;
    $(".changeUnits").click(function() {

      if (shown == 1) {
        $("#fahrenheit").css("display", "none");
        $("#celsius").css("display", "inline-block");
        $(".degrees").html(truncatedMetric);
        shown = 2;

      } else {
        $("#celsius").css("display", "none");
        $("#fahrenheit").css("display", "inline-block");
        $(".degrees").html(truncatedImperial);
        shown = 1;
      }
    });

    if (kelvinDegrees > 291.48) {
      $('.weather').addClass('weather-hot');
    } else if (kelvinDegrees < 291.48 && kelvinDegrees > 269.26) {
      $('.weather').addClass('weather-temperate');
    } else {
      $('.weather').addClass('weather-cold');
    }

  });

});

// Get user defined location on click/prompt here
$(".changeLocation").on("click", function() {
  //Define new location via prompt
  var newLocation = prompt("Enter your destination, please:");
  //Set new location on the page
  $(".location").html(newLocation);
  //Get new weather data based on new location
  var getWeather = $.ajax({
    type: 'GET',
    url: "http://api.openweathermap.org/data/2.5/weather?q='" + newLocation + "&APPID=4b3ff62e3ed31d05cb44a014d891b7e6",
  });
  // Once received - repeat previous process to set new background image, etc
  getWeather.done(function(data) {

    temp = data.main.temp;

    var kelvinDegrees = temp;
    var imperialDegrees = ((kelvinDegrees * (9 / 5)) - 459.67);
    var truncatedImperial = Math.floor(imperialDegrees * 100) / 100;
    var metricDegrees = kelvinDegrees - 273.15;
    var truncatedMetric = Math.floor(metricDegrees * 100) / 100;

    $(".degrees").html(truncatedImperial);

    var shown = 1;
    $(".changeUnits").click(function() {

      if (shown == 1) {
        $("#fahrenheit").css("display", "none");
        $("#celsius").css("display", "inline-block");
        $(".degrees").html(truncatedMetric);
        shown = 2;

      } else {
        $("#celsius").css("display", "none");
        $("#fahrenheit").css("display", "inline-block");
        $(".degrees").html(truncatedImperial);
        shown = 1;
      }
    });

    if (kelvinDegrees > 291.48) {
      $('.weather').addClass('weather-hot');
    } else if (kelvinDegrees < 291.48 && kelvinDegrees > 269.26) {
      $('.weather').addClass('weather-temperate');
    } else {
      $('.weather').addClass('weather-cold');
    }
  });
});

这是 HTML:

<html>

<body>

  <div class="weather">

    <div class="ship">

      <div class="container">

        <div class="eighty"></div>

        <div class="twenty">
          <div class="thirty-2">

            <div class="status">
              Loc: <span class="location"></span><br><br> Temp: <span class="degrees"></span>&#176; <span id='fahrenheit'>F</span>
              <span id='celsius' style='display:none;'>C</span><br><br> Cond:
            </div>
            <div class="thirty-2-2"></div>
            <div class="controls">
              <input type="image" id="buttons" class="changeLocation" src="http://i1079.photobucket.com/albums/w513/spudees/img_0531_31979702762_o_zps3nxo0l9w.png" data-alt-image="http://i1079.photobucket.com/albums/w513/spudees/img_0532_32128262395_o_zpsgqmta3cy.png"
              /><br><br>
              <input type="image" id="buttons" class="changeUnits" src="http://i1079.photobucket.com/albums/w513/spudees/img_0534_31979680392_o_zps5t3o2w7w.png" data-alt-image="http://i1079.photobucket.com/albums/w513/spudees/img_0533_32128259015_o_zpsijybngnw.png"
              />
            </div>

          </div>

        </div>

      </div>

    </div>

</body>

</html>

和 CSS:

html,
body {
  min-height: 100%;
  background-image: url("https://i.ytimg.com/vi/JquobII5VjA/maxresdefault.jpg");
  margin: 0;
  padding: 0;
}

.weather-cold {
  min-height: 100vh;
  max-width: 100vw;
  margin: auto;
  padding: 0;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  background-image: url("https://blenderartists.org/forum/attachment.php?attachmentid=416901&d=1451562942");
}

.weather-temperate {
  min-height: 100vh;
  max-width: 100vw;
  margin: auto;
  padding: 0;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: top;
  background-image: url("http://vignette3.wikia.nocookie.net/starwars/images/9/9c/Endor_matte.jpg/revision/latest?cb=20070811234822");
}

.weather-hot {
  min-height: 100vh;
  max-width: 100vw;
  margin: auto;
  padding: 0;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  background-image: url("https://content.pulse.ea.com/content/starwars-ea-com/en_US/starwars/battlefront/news-articles/the-star-wars-battlefront-planets--creating-tatooine/_jcr_content/featuredImage/renditions/rendition1.img.jpg");
}

.ship {
  height: 100vh;
  position: relative;
  background: url("http://i.imgur.com/LIWZWHP.png")no-repeat;
  background-size: 100% 100%;
  background-position: center;
}

.changeLocation {
  margin-top: 15px;
}

.container {
  min-height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.eighty {
  min-height: 82vh;
  background-color: blue;
  margin: 0;
  padding: 0;
  visibility: hidden;
}

.twenty {
  min-height: 18vh;
  min-width: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-content: center;
}

.thirty-2 {
  min-width: 30vw;
  display: inline-block;
  margin: 0;
  padding: 0;
  text-align: center;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-content: center;
}

.thirty-2-2 {
  width: 6%;
  display: inline-block;
  margin: 0;
  padding: 0;
}

.status {
  height: 60%;
  width: 30%;
  display: inline-block;
  background-color: #0f1817;
  z-index: 200;
  color: #5cc35c;
  font-family: helvetica;
  font-size: 2.3vmin;
  text-align: left;
}

.controls {
  height: 80%;
  width: 30%;
  display: inline-block;
  margin: 0;
  padding: 0;
  background-color: #0f1817;
  z-index: 200;
  color: #5cc35c;
  font-family: helvetica;
  font-size: 2.5vmin;
}

#buttons {
  max-width: 100%;
  height: auto;
  width: auto\9;
  /* ie8 */
}

最佳答案

如果我理解您的目的,那么玩弄您的示例是因为您只添加类,从不删除它,所以在您第二次单击时,您仍然拥有第一个 weather-xyz。

您需要删除您添加的现有类或以其他方式清除您添加的第一个类,例如。

$('.weather').removeClass('weather-hot');

关于javascript - 添加第二个类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498448/

相关文章:

javascript - 表达 "Cannot GET/query"错误

javascript - 从包含页面的 jsonp api 检索数据

javascript - MySQL 表填充下拉列表。选择后,将填充第二个下拉列表

javascript - SOAP Web 服务错误 :Response to preflight request does not pass access control check 'Access-Control-Access-Origin' using SOAPClient. js

jquery - 为什么我不能将绑定(bind)方法挂接到此类?

javascript - 最佳实践工厂 angular.js 1.2

javascript - 无法使用 jquery 选择新创建的对象

Javascript 显示和隐藏

jQuery .ready() 适用于多种形式

html - css background-height 使元素溢出