我有問題,我必須點擊兩次才能在第一次單擊時交換按鈕文本和類。所有其他時間在第一次點擊時發生變化。 我已經嘗試刪除單擊changeUnits()函數內部,但在這種情況下,我可以更改爲Celcius一次,不能再交換值。我正在分配價值和班級,因爲我打算稍後在另一個API調用中使用它來檢索指定單元中的天氣。 有沒有人看到我在做什麼錯了?不得不點擊兩次執行onclick
HTML
<button id="units" class="Fahrenheit" onclick="changeUnits();callWeather()">F</button>
的JavaScript
function changeUnits() {
if($("#units").hasClass("Fahrenheit")) {
$(".Fahrenheit").click(function() {
$(".Fahrenheit").text("C");
$(this).removeClass('Fahrenheit').addClass('Celcius');
});
}
else if($("#units").hasClass("Celcius")) {
$(".Celcius").click(function() {
$(".Celcius").text("F");
$(this).removeClass('Celcius').addClass('Fahrenheit');
});
}
}
你執行首先點擊你的'changeUnits()'和在該功能你設定另一個點擊監聽器 - 這就是爲什麼你必須點擊兩次。刪除不必要的監聽器('$(「。Fahrenheit」)。click(function(){'and'$(「。Celcius」)。click(function(){'),它將按預期工作。 –