2017-08-27 66 views
-1

我想切換一個div,以便點擊時它會將溫度轉換爲華氏度,當再次單擊它時,它將恢復到最初由api拉入的攝氏溫度讀數。切換div中包含的HTML

時,我只處理與數字代碼工作:

var fahrenheit = (data.main.temp * 1.8 + 32).toFixed(2); 
var celsius = data.main.temp; 

$("#temp").on("click", function() { 
$("#temp").html($("#temp").html() == fahrenheit ? celsius : fahrenheit) 

}); 

但是當我嘗試添加文本到HTML它不工作,就會切換一次華氏轉換,但不再次點擊時切換回來。

var fahrenheit = (data.main.temp * 1.8 + 32).toFixed(2); 
var celsius = data.main.temp; 

$("#temp").on("click", function() { 
$("#temp").html($("#temp").html() == fahrenheit + "&deg F" ? celsius + "&deg C" : fahrenheit + "&deg F") 

}); 

我對此有點難住。我搜索了一下,但似乎無法找到適合我想要的解決方案。

感謝您的任何幫助。

這裏是我的codepen

+0

所以'#temp'是...?請包括標記。 – 82Tuskers

+0

對不起,新手使用本網站#temp是一個元素的ID。我將編輯我的原始文章,以包含指向codepen的鏈接。感謝您的高舉。 – Seekingcat

+0

我的猜測是它可能與'&deg'有關。當把它放在html中時,它轉向'°',這將如何比較? –

回答

1

你的問題的鏈接是通過JavaScript檢查的onclick。

當你選擇了它,你是使用JavaScript這樣,而不是使用度的HTML實體,你只需要使用度字符:

更改此:

$("#temp").html($("#temp").html() == fahrenheit + "&deg F" ? celsius + "&deg C" : fahrenheit + "&deg F") 

這樣:

$("#temp").html($("#temp").html() == fahrenheit + "° F" ? celsius + "° C" : fahrenheit + "° F") 
+0

謝謝你。我的問題很簡單,顯然表明我缺乏經驗。這是完美的。 – Seekingcat

+0

無需擔心和快樂的編碼與您的天氣應用:) – quirimmo

0

您必須檢查當前是否顯示攝氏溫度,然後根據該溫度做出決定

$("#temp").on("click", function() { 
    var isCelsius = $(this).html().indexOf('C') > -1; 
    $('#temp').html(isCelsius ? celsius + '&deg C' : fahrenheit + '&deg F'); 
}); 
0

當您使用html()獲取解析HTML的值時,您沒有&degHTML實體但解析了值。

要修復您的代碼,您可以比較度實體的十六進制值。

$("#temp").on("click", function() { 
    $("#temp").html($("#temp").text() == fahrenheit + "\xB0 F" ? celsius + "\xB0 C" : fahrenheit + "\xB0 F") 
}); 
1

您只能比較數字(沒有最後3°F或°C字符)。

var fahrenheit = (data.main.temp * 1.8 + 32).toFixed(2); 
 
var celsius = data.main.temp; 
 

 
$("#temp").on("click", function() { 
 
    var numberOnly = $("#temp").html().length - 3; 
 
    $("#temp").html($("#temp").html().substring(0, numberOnly) == fahrenheit ? celsius + "&deg C" : fahrenheit + "&deg F"); 
 
});