按钮来回更改文本 JS

Button to change text back and forth JS

我正在尝试制作一个按钮,在点击时将温度更改为华氏度,但如果再次单击它,则会将温度更改回摄氏度。如果您单击温度符号(即摄氏度),它应该将温度更改为华氏度。如果华氏符号,它应该再次显示摄氏温度。

问题是我当前的按钮将温度更改为华氏度并立即将其更改回摄氏度。

在我的研究中,我找到了 toggle() jquery 函数,但它现在似乎已被弃用,老实说,我不太明白如何使用 it.n

我也发现了这个 Whosebug 问题,但不知道如何将答案应用到我的情况:

谢谢!

var currentTemp= "cel";
  $("#tempUnit").click(function(){

  alert("Temperature Changed to Fahrenheit.");
//   var currentTemp= cel;
    if (currentTemp=== "cel") {
    currentTemp = "faren"; 
      var farCalc=  (data.main.temp * 1.8) + 32;

   $('#temp').html("Temperature:" + Math.round(farCalc) +"");
     $('#tempUnit').html("&#8457");
   }
    if (currentTemp=== "faren"){

  alert("Temperature Changed to Celsius");
   $('#temp').html("Temperature:" + data.main.temp +"");
     $('#tempUnit').html("&#8451");  
      } 

在此处查看完整代码:https://codepen.io/mso122591/pen/XZZWPR

The problem is that my current button changed the temperature to Fahrenheit and immediately changes it back to Celsius.

发生这种情况是因为您第一次在条件 if (currentTemp=== "cel") 中将 currentTemp = "faren" 设置为 return 为真,然后您再次使用 if 条件而不是您应该像这样使用 else 块

var currentTemp = "cel";
$("#tempUnit").click(function() {

      alert("Temperature Changed to Fahrenheit.");
      //   var currentTemp= cel;
      if (currentTemp === "cel") {
        currentTemp = "faren";
        var farCalc = (data.main.temp * 1.8) + 32;

        $('#temp').html("Temperature:" + Math.round(farCalc) + "");
        $('#tempUnit').html("&#8457");
      }
      else {
         currentTemp = "cel";
        alert("Temperature Changed to Celsius");
        $('#temp').html("Temperature:" + data.main.temp + "");
        $('#tempUnit').html("&#8451");
      }

P.S 再次在 else 块中设置 currentTemp = "cel";

首先,codepen 看起来破烂不堪,而且说实话非常难以阅读。我在尝试之前就放弃了。所以我会以一种描述我将如何解决问题的方式回答。

首先将您的职责分解为不同的功能。然后将这些功能连接在一起。您将管理状态(在这种情况下,您当前所处的学位。最后将结果和用户单击时的事件处理程序附加到 DOM。每个都是它自己的自包含函数。

$(function() {

var TEMP_SYMBOLS = {
  celceus: '&#8451',
  fahrenheit: '&#8457'
};

var TEMP_CONVERTERS = {
  celceus: function(temp) { return temp; },
  fahrenheit: function(temp) { return (temp * 1.8) + 32; }
};

var currentTemp = 0;
var currentTempMode = 'celceus';

function fetchTemp() {
  // Here is where you fetch the temp from AJAX.
  // For demonstration purposes we will simply hard code a value.
  currentTemp = 32.4;
}

function renderTemp() {
  var symbol = TEMP_SYMBOLS[currentTempMode];
  var converter = TEMP_CONVERTERS[currentTempMode];
  var value = converter(currentTemp);
  $('#temp-output').html('Temperature: ' + value + ' ' + symbol);
}

fetchTemp();
renderTemp();

$('#temp-output').on('click', function() {
  currentTempMode = currentTempMode === 'celceus' ? 'fahrenheit' : 'celceus';
  renderTemp();
});

});
#temp-output {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="temp-output">Loading&hellip;</span>