簡體   English   中英

按鈕來回切換JS文字

[英]Button to change text back and forth JS

我試圖制作一個將溫度更改為華氏度的按鈕,但是如果再次單擊將溫度更改為攝氏溫度。 如果單擊溫度符號(即攝氏),則應將溫度更改為華氏度。 如果是華氏符號,則應再次以攝氏度為單位顯示溫度。

問題是我當前的按鈕將溫度更改為華氏度,並立即將其更改回攝氏溫度。

在我的研究中,我找到了toggle() jQuery函數,但現在似乎已棄用該函數,老實說,我不太了解如何使用它。

我也找到了這個stackoverflow問題,但是不知道如何將答案應用於我的情況: 使用Bootstrap和jquery來回切換按鈕文本

謝謝!

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

問題是我當前的按鈕將溫度更改為華氏度,並立即將其更改回攝氏溫度。

發生這種情況是因為您在條件if (currentTemp=== "cel")中設置currentTemp = "faren" ,該條件首次返回true,然后再次使用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"); } 

PS再次設置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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM